void RemoveNodes(SharpTreeNode start, SharpTreeNode end) { // Removes all nodes from start to end (inclusive) // All removed nodes will be reorganized in a separate tree, do not delete // regions that don't belong together in the tree model! List <SharpTreeNode> removedSubtrees = new List <SharpTreeNode>(); SharpTreeNode oldPos; SharpTreeNode pos = start; do { // recalculate the endAncestors every time, because the tree might have been rebalanced HashSet <SharpTreeNode> endAncestors = new HashSet <SharpTreeNode>(); for (SharpTreeNode tmp = end; tmp != null; tmp = tmp.listParent) { endAncestors.Add(tmp); } removedSubtrees.Add(pos); if (!endAncestors.Contains(pos)) { // we can remove pos' right subtree in a single step: if (pos.right != null) { removedSubtrees.Add(pos.right); pos.right.listParent = null; pos.right = null; } } SharpTreeNode succ = pos.Successor(); DeleteNode(pos); // this will also rebalance out the deletion of the right subtree oldPos = pos; pos = succ; } while (oldPos != end); // merge back together the removed subtrees: SharpTreeNode removed = removedSubtrees[0]; for (int i = 1; i < removedSubtrees.Count; i++) { removed = ConcatTrees(removed, removedSubtrees[i]); } }