Python 3D Academyবাংলা

Inserting, and the three cases of deleting

🌍 In real life. A librarian shelving a new book doesn't shuffle the whole library. She walks to where the book would be if it were already there, and puts it in that gap. Taking a book out is the harder job. If it stands at the end of a row, she simply removes it. If a single run of books depends on its place, they shift up into it. And if it holds a spot that two runs of books depend on, she fills that spot with the very next book in order, so nothing else has to move.

A binary search tree changes the same way: inserting puts a new leaf exactly where a search would look for it, and deleting has three cases, depending on how many children the node has.

The idea in one sentence: to insert x, search for it and hang it as a new leaf where the search falls off the tree; to delete a node, take it off if it is a leaf, let its only child move up if it has one, and if it has two, replace its value with its successor's and delete the successor instead.

Its words:

  • insert: add a value, keeping the BST rule
  • delete: remove a value, keeping the BST rule
  • successor: the next bigger value in the tree; for a node with a right subtree it is the leftmost node of that subtree (go right once, then left as far as possible)
  • predecessor: the next smaller value (go left once, then right as far as possible); it works for deleting too

How inserting works, step by step:

  1. search for x as in Lesson 48.1
  2. if you find it, it is already there: do nothing
  3. when the side you need is empty, put a new node with x there

How deleting works, once the node d holding x is found:

  1. a leaf: just take it off
  2. one child: that child, with everything under it, moves up into d's place
  3. two children: find the successor s, copy its value into d, then delete s from the right subtree; s has no left child, so removing it is case 1 or 2

First two inserts, each ending in a new leaf:

Now the three kinds of delete in one tree: 1 is a leaf, 7 has one child (6), and the root 5 has two, so its successor, 6, is copied up:

Why it is correct. Inserting: the new leaf goes where the search for x ended, and on the way down x was compared with every ancestor and sent to the correct side of each one. So it sits on the correct side of every node above it, and the rule still holds. Deleting a leaf removes a node that nothing hangs from. Deleting a node with one child: that child's whole subtree was already on the correct side of every ancestor of d (it was under d), so it can take d's place. Deleting a node with two children: the successor s is the smallest value in d's right subtree. So s is bigger than everything in d's left subtree (they are smaller than d, and s is bigger than d) and smaller than everything left in d's right subtree. Putting s's value in d's place keeps the rule on both sides, and s itself has no left child (it is the leftmost node), so removing it is one of the two easy cases.

What it costs, by counting. Inserting is a search plus one new node: at most h comparisons. Deleting is a search for x, then, for a node with two children, a walk down to the successor and a second walk along the same branches to remove it: together at most about 2h steps. Both are O(h): O(log n) in a balanced tree, O(n) in a chain. Compare a sorted Python list, where finding the place is fast with bisect but insert must shift every item after it: O(n) moves.

class Node:
    def __init__(self, val, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def insert(root, x):
    if root is None:
        return Node(x)                # the empty spot the search reached: x goes here
    if x < root.val:
        root.left = insert(root.left, x)
    elif x > root.val:
        root.right = insert(root.right, x)
    return root                       # x already there: nothing changes

def delete(root, x):
    if root is None:
        return None                   # x is not in the tree
    if x < root.val:
        root.left = delete(root.left, x)
    elif x > root.val:
        root.right = delete(root.right, x)
    else:
        if root.left is None:         # a leaf, or only a right child
            return root.right
        if root.right is None:        # only a left child
            return root.left
        succ = root.right             # two children: the successor is the
        while succ.left is not None:  # smallest value in the right subtree
            succ = succ.left
        root.val = succ.val           # copy it up...
        root.right = delete(root.right, succ.val)   # ...and remove the old one
    return root

def inorder(node):
    return [] if node is None else inorder(node.left) + [node.val] + inorder(node.right)

root = None
for x in [5, 3, 8, 1, 4, 7, 9]:
    root = insert(root, x)       # always keep what insert returns
print(inorder(root))
root = delete(root, 1)           # a leaf
root = delete(root, 8)           # two children: 9 is the successor
root = delete(root, 5)           # the root, two children: 7 is the successor
print(root.val, inorder(root))

Mistakes and edge cases.

  • not keeping what is returned: insert(root.left, x) on its own builds a new node and loses it; write root.left = insert(root.left, x), and root = insert(root, x) at the top, because inserting into an empty tree makes a new root
  • deleting the root: the root can change (when it has one child, or none), so the caller must also do root = delete(root, x)
  • two children, wrong replacement: copying in any value other than the successor or the predecessor (the right child's, say, when it has a left subtree) breaks the rule for the nodes around it
  • forgetting to remove the old successor: its value would then be in the tree twice
  • a value that isn't there: insert hangs it; delete walks to None and changes nothing
  • duplicates: this lesson's trees keep each value once; trees that allow repeats must choose a side for them (say, always the right) and stick to it

Quiz

  1. Inserting 4, 2, 6, 1 into an empty BST. What does this print?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def insert(root, x):
        if root is None:
            return Node(x)                # the empty spot the search reached: x goes here
        if x < root.val:
            root.left = insert(root.left, x)
        elif x > root.val:
            root.right = insert(root.right, x)
        return root                       # x already there: nothing changes
    
    root = None
    for x in [4, 2, 6, 1]:
        root = insert(root, x)
    print(root.val, root.left.val, root.right.val, root.left.left.val)
  2. In the tree [5, 3, 8, 1, 4, 7, 9], what is the successor of 5?

    • 7: go right to 8, then left as far as possible
    • 8: its right child
    • 4: the biggest value on its left
  3. What does this print?

    class Node:
        def __init__(self, val, left=None, right=None):
            self.val = val
            self.left = left
            self.right = right
    
    def delete(root, x):
        if root is None:
            return None                   # x is not in the tree
        if x < root.val:
            root.left = delete(root.left, x)
        elif x > root.val:
            root.right = delete(root.right, x)
        else:
            if root.left is None:         # a leaf, or only a right child
                return root.right
            if root.right is None:        # only a left child
                return root.left
            succ = root.right             # two children: the successor is the
            while succ.left is not None:  # smallest value in the right subtree
                succ = succ.left
            root.val = succ.val           # copy it up...
            root.right = delete(root.right, succ.val)   # ...and remove the old one
        return root
    
    root = Node(5, Node(3, Node(1), Node(4)), Node(8, Node(7), Node(9)))
    root = delete(root, 3)
    print(root.left.val, root.left.left.val, root.left.right)
  4. With this insert, some new values silently go missing: inserting 6 into [5, 3, 8, 1, 4, 7, 9] changes nothing. Which line is wrong?

    def insert(root, x):
        if root is None:
            return Node(x)
        if x < root.val:
            insert(root.left, x)
        elif x > root.val:
            root.right = insert(root.right, x)
        return root
  5. Why is the successor of a node with two children safe to remove after copying it up?

    • It is the leftmost node of the right subtree, so it has no left child: removing it is the leaf or one-child case
    • It is always a leaf
    • It is always the root's right child

Coding tasks

  1. Write insert(root, x): add x to the BST as a new leaf and return the root (a new root if the tree was empty). If x is already there, leave the tree as it is.

  2. Write delete(root, x): remove x from the BST, keeping the BST rule, and return the root (it may change). A node with two children takes its successor's value, and the successor is removed instead. If x is not there, change nothing.