Sub topic 10
Inserting into a BST
This chapter assumes you know recursion, object references, and Big-O notation. It also assumes you have met the binary search tree (BST) property and BST search from the previous chapters. Insertion builds directly on search. It follows the same path and then attaches a new node where the search would have ended.
The idea
A BST stores distinct keys so that, for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. To insert a key k, you do the following:
- Start at the root.
- If
kis smaller than the current key, go left. If it is larger, go right. - When the next child is empty, put a new node there.
The new node always becomes a leaf. Insertion never moves or changes existing nodes. It only fills one empty child slot. That empty slot is the place where an unsuccessful search for k would have stopped.
The code
The Node class is the one used in the traversal chapter. The recursive version returns the root of the (possibly new) subtree, so the caller reattaches the result.
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert(node, key):
if node is None:
return Node(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
return node
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
root = None
for k in [50, 30, 70, 20, 40, 60, 80, 40]:
root = insert(root, k)
keys = []
inorder(root, keys)
print(keys)This prints [20, 30, 40, 50, 60, 70, 80]. The second 40 was ignored because the tree already holds that key.
How the recursion works
- Base case.
node is Nonemeans we have reached an empty slot. We create and return a newNode. - Recursive case. We insert into the correct subtree, then assign the returned subtree root back to
node.leftornode.right. - Reassignment is mostly redundant. On the way back up, each assignment stores the same child that was already there. Only the last one, at the empty slot, changes anything. The pattern is still worth using, because it handles the empty-tree case and the same style carries over to deletion and to rotations in AVL trees.
- Duplicates. When
key == node.key, neither branch runs, and the tree is unchanged.
Worked example
Insert the keys 50, 30, 70, 20, 40, 60, 80 into an empty BST, in that order.
- 50 goes in the empty tree and becomes the root.
- 30 is less than 50, so it goes left of 50.
- 70 is greater than 50, so it goes right of 50.
- 20 is less than 50 and less than 30, so it goes left of 30.
- 40 is less than 50 and greater than 30, so it goes right of 30.
- 60 is greater than 50 and less than 70, so it goes left of 70.
- 80 is greater than 50 and greater than 70, so it goes right of 70.
This tree is perfect: height 2 with 7 nodes. It is the best case for these keys, and it happened because the order of insertion was favorable.
An iterative version
Recursion uses stack space proportional to the height. An iterative version uses constant extra space. It tracks the parent so it can attach the new node.
def insert_iter(root, key):
new = Node(key)
if root is None:
return new
parent = None
cur = root
while cur:
parent = cur
if key < cur.key:
cur = cur.left
elif key > cur.key:
cur = cur.right
else:
return root # duplicate: do nothing
if key < parent.key:
parent.left = new
else:
parent.right = new
return rootThe loop ends when cur falls off the tree. At that point parent is the last real node visited, and the new node goes on the correct side of it. The comparison with parent.key is needed because the loop does not record which direction it last took.
Insertion order decides the shape
The same set of keys can produce many different trees. The shape depends only on the order in which keys arrive.
| Insertion order | Resulting shape | Height |
|---|---|---|
| 50, 30, 70, 20, 40, 60, 80 | Perfect | 2 |
| 20, 30, 40, 50, 60, 70, 80 | Right-skewed chain | 6 |
| 80, 70, 60, 50, 40, 30, 20 | Left-skewed chain | 6 |
| 40, 20, 60, 10, 30, 50, 70 | Perfect, different root | 2 |
A sorted or reverse-sorted input produces a skewed tree, which is effectively a linked list. This is the classic worst case, and it is a common GATE question.
Cost of insertion
Insertion visits one node per level on its path from the root to the empty slot, then does constant work to create the node. If the tree has height h, the cost is O(h).
- Best and average case for balanced input. If the tree stays close to balanced,
his aboutlog2 n, so insertion isO(log n). For keys inserted in random order, the expected height is alsoO(log n). - Worst case. If the tree is a chain,
h = n - 1, so inserting the next key costsO(n). - Building a whole tree. Inserting
nkeys one by one costsO(n log n)for a balanced result andO(n^2)for the skewed case. In the skewed case, thei-th insertion walks pasti - 1existing nodes, giving 0 + 1 + ... + (n-1) = n(n-1)/2 comparisons.
The cost is a function of height, not of n directly. This is why the later chapter on AVL trees matters: it keeps h at O(log n) regardless of input order.
Common errors and edge cases
- Forgetting to reassign the result. Writing
insert(node.left, key)withoutnode.left = ...loses the new node when the child wasNone. The new node is created, returned, and thrown away. - Forgetting to reassign at the top level. For an empty tree,
insert(root, k)returns the new root. You must writeroot = insert(root, k). - Mishandling duplicates. This chapter's code ignores them. Some textbooks put equal keys in the left or right subtree instead. When a GATE question does not say, read it carefully. If it says "distinct keys", duplicates do not arise.
- Assuming a new node can become the root of a bigger subtree. In a plain BST it cannot. New nodes are always leaves. Only the rotations of self-balancing trees change which node is the root of a subtree.
- Confusing insertion order with sorted order. The inorder traversal is always sorted, whatever the insertion order. The preorder traversal, however, reflects insertion order: for a BST, inserting the keys in preorder sequence rebuilds exactly the same tree.
Why the new node is always a leaf
Take any BST and a key k that is not in it. Searching for k follows one path. At each node on that path the comparison is forced by the BST property. The search ends at an empty child slot, because every node on the path had a child in the direction it needed to go, until the last one did not. Placing k in that slot keeps the property for every ancestor: k is on the correct side of each of them, since it took exactly the branches the comparisons demanded. No other node is affected, so the property holds for the whole tree. The slot is empty, so the new node has no children and is a leaf.
Summary of key facts
- Insertion follows the search path and attaches a leaf at the empty slot where the search fails.
- A BST with distinct keys ignores a duplicate, or follows a stated convention.
- The cost is
O(h):O(log n)for a balanced tree andO(n)for a skewed one. - Insertion order, not the key set, determines the shape.
- Sorted input gives a skewed tree of height
n - 1.
Exercise
Insert the keys 45, 20, 60, 10, 30, 50, 70, 25 into an empty BST, in that order. What is the height of the tree, and what is the parent of 25?
Show answer
45 is the root. 20 goes left of 45 and 60 goes right. 10 goes left of 20 and 30 goes right of 20. 50 goes left of 60 and 70 goes right of 60. 25 is less than 45, greater than 20, less than 30, so it becomes the left child of 30. The longest root-to-leaf path is 45, 20, 30, 25, which has 3 edges, so the height is 3. The parent of 25 is 30.
Exercise
How many key comparisons are needed in total to build a BST by inserting 1, 2, 3, 4, 5 in that order into an empty tree? Count one comparison per node passed on the way down, and nothing for the first key.
Show answer
The first key needs 0 comparisons. Key 2 is compared with 1 (1 comparison). Key 3 is compared with 1 and 2 (2). Key 4 needs 3, and key 5 needs 4. The total is 0 + 1 + 2 + 3 + 4 = 10, which equals n(n-1)/2 for n = 5.
Exercise
A BST is built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13 into an empty tree. Write its preorder traversal, and say what happens if you insert that preorder sequence into a fresh empty BST.
Show answer
The tree has root 8. Node 3 has children 1 and 6. Node 6 has children 4 and 7. Node 10 has right child 14, and 14 has left child 13. The preorder traversal is 8, 3, 1, 6, 4, 7, 10, 14, 13. This is the same as the insertion order of the nodes in the subtrees reordered so every parent comes before its children. Inserting this sequence into a fresh BST gives exactly the same tree, because each node appears after all of its ancestors, so each key is attached at the same position as before.