Sub topic 10
Inserting into a Binary Search Tree
Assume you know recursion, object references, arrays, linked lists, and Big-O notation. This chapter uses the binary search tree property to insert a new key while preserving the tree's ordering.
A binary search tree (BST) stores keys so that, for every node:
- Every key in the left subtree is smaller than the node's key.
- Every key in the right subtree is larger than the node's key.
This rule determines the path taken by a new key. Compare the key with the current node, then move left if it is smaller or right if it is larger. Continue until an empty child position is found.
Recursive insertion
Suppose a BST contains 8, 3, 10, 1, and 6. To insert 4:
- Compare 4 with 8. Move left.
- Compare 4 with 3. Move right.
- Compare 4 with 6. Move left.
- The left child of 6 is empty, so place 4 there.
The recursive function reaches an empty position and creates a node there. Each recursive call returns the root of the subtree it has updated. This return value is important when the inserted node becomes the root of an empty subtree.
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)
# Equal keys are ignored in this version.
return node
def inorder(node):
if node is not None:
inorder(node.left)
print(node.key, end=" ")
inorder(node.right)
root = None
for value in [8, 3, 10, 1, 6, 4]:
root = insert(root, value)
inorder(root)The output is:
1 3 4 6 8 10The root = insert(root, value) assignment handles the first insertion. When root is None, insertion returns the newly created node. For later insertions, it returns the unchanged root after updating one of its subtrees.
Duplicate keys
A BST must define how it handles equal keys. Common choices are:
| Duplicate policy | Effect |
|---|---|
| Ignore duplicates | The tree stores only distinct keys |
| Store equal keys on one side | Equal keys become ordinary nodes |
| Store a count | One node records how many times the key occurs |
The code above ignores duplicates. This choice is useful when the BST represents a set. If the tree represents a multiset, storing a count avoids creating an arbitrary chain of equal keys.
Cost of insertion
Let h be the height of the tree, measured as the number of edges on the longest root-to-leaf path. Insertion visits one root-to-leaf path, so its time cost is O(h). The recursive version uses O(h) extra stack space.
For a balanced tree with n nodes, h is O(log n), so insertion is O(log n). If keys arrive in sorted order, an ordinary BST can become a chain. Its height is then n - 1, and insertion can cost O(n).
Exercise
If a BST contains 10, 5, 15, and 12, where is key 13 inserted?
Show answer
Compare 13 with 10 and move right, compare it with 15 and move left, then compare it with 12 and move right. Key 13 becomes the right child of 12.