Sub topic 5
Inserting a key
This chapter assumes you know recursion, basic Python classes, and introductory Big-O. It also assumes you have seen the BST ordering property and the Node class and search function from earlier chapters. Insertion builds directly on search.
The idea: search, then attach
A BST has no free slots. Every new key goes in as a new leaf, at the position where a search for that key would have ended. Search follows the ordering property: go left if the key is smaller, right if it is larger. When it reaches an empty child reference (None), the key is not in the tree, and that empty spot is exactly where the key belongs.
So insertion is a search that ends by creating a node. Existing nodes never move.
The code
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 nodeinsert returns the root of the subtree it was given. Each call reassigns the child it recursed into:
- If
nodeisNone, the function returns a newNode. The caller stores it as its child, which attaches the leaf. - Otherwise it recurses into one side and stores the returned subtree root back into
node.leftornode.right. - Every other call returns the same node it received, so these reassignments change nothing.
Build a tree by assigning the result back to the root:
root = None
for k in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, k)
print(root.key) # 50
print(root.left.key) # 30
print(root.right.left.key) # 60The first key becomes the root. Every later key is placed relative to the nodes already present, so the same keys inserted in a different order can produce a different tree.
Common errors
- Forgetting to assign the result. Writing
insert(root, 45)withoutroot = ...works for a non-empty tree, because the existing nodes are mutated. It silently fails whenrootisNone, since the new node is returned and discarded. - Discarding the return value inside the recursion. Writing
insert(node.left, key)without assigning tonode.leftnever attaches the new node. - Missing the equal case. In this version, a key equal to
node.keymatches neither branch. The function returns the tree unchanged, so duplicates are ignored. If you usedelseinstead ofelif key > node.key, equal keys would go right and duplicates would be stored. - Comparing unlike types. Mixing
intandstrkeys raisesTypeErrorin Python 3 at the first comparison.
Cost
Insertion visits one node per level on its path, doing constant work at each. The cost is O(h), where h is the tree height. With keys arriving in random order the height tends to stay near log n. With sorted input it grows to n, and each insertion costs O(n).
Iterative alternative
If recursion depth is a concern, track the parent while descending:
def insert_iterative(root, key):
if root is None:
return Node(key)
parent, node = None, root
while node is not None:
if key == node.key:
return root
parent = node
node = node.left if key < node.key else node.right
if key < parent.key:
parent.left = Node(key)
else:
parent.right = Node(key)
return rootThis uses O(1) extra space and has the same O(h) time.
Exercise
Starting from an empty tree, you insert 8, 3, 10, 1, 6 in that order, then insert 6 again. What is the left child of 3, the right child of 3, and how many nodes does the tree have at the end?
Show answer
The left child of 3 is 1 and the right child of 3 is 6. The tree has 5 nodes, because the second insert of 6 matches neither branch and leaves the tree unchanged.
Exercise
Why does insert return node at the end instead of returning nothing?
Show answer
The caller assigns the return value to a child reference. Returning the same node keeps existing links unchanged, and returning a new Node for a None position is what attaches the new leaf.