Sub topic 11
Height and the Cost of Each Operation
This chapter assumes you can read the Node, search, insert, and delete code from earlier chapters, and that you know basic Big-O notation. Here we tie the cost of every operation to one number: the height of the tree.
What height means
The height of a tree is the number of edges on the longest path from the root down to a leaf. An empty tree has height -1, and a tree with a single node has height 0. This is the convention the code below uses.
Each operation starts at the root and moves down one level per step. It never moves back up and never visits a second branch at the same level. So the number of steps is bounded by the height, not by the number of keys.
Why each operation costs O(h)
Let h be the height and n the number of keys.
| Operation | Work per level | Worst-case cost |
|---|---|---|
| Search | One comparison, go left or right | O(h) |
| Insert | One comparison, then attach a new leaf | O(h) |
| Delete | One comparison, plus finding the successor if the node has two children | O(h) |
| Minimum or maximum | Follow only left or only right links | O(h) |
Deletion needs a closer look. A node with two children triggers minimum(node.right), and then a second descent to remove the successor. Each descent goes down once, and together they never go deeper than the tree's height. So the total is still O(h), at most about twice the height.
Measuring height in code
This function computes height with the same -1 convention.
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 height(node):
if node is None:
return -1
return 1 + max(height(node.left), height(node.right))
balanced = None
for k in [3, 1, 5, 2, 4]:
balanced = insert(balanced, k)
chain = None
for k in [1, 2, 3, 4, 5]:
chain = insert(chain, k)
print(height(balanced)) # 2
print(height(chain)) # 4Both trees hold the same five keys. Insertion order alone changes the height from 2 to 4. A search for 5 in balanced takes three comparisons, and the same search in chain takes five.
Height as a function of n
The height ranges between two extremes.
- Best case: the tree is as full as possible. Each level holds about twice as many nodes as the one above, so n keys fit in a tree of height about log2(n). For 1,000,000 keys that is about 20.
- Worst case: every node has at most one child. The height is n - 1, which for 1,000,000 keys is 999,999.
So the cost of each operation is O(log n) for a well-shaped tree and O(n) for a chain. A plain BST gives no guarantee about which one you get. The average case is better than the worst: inserting keys in random order gives an expected height of O(log n). That figure depends on the order being random, which real data often is not.
Common errors
- Counting nodes instead of edges. A single node has height 0 here, so a path of five nodes has height 4. Check which convention a textbook or library uses before comparing numbers.
- Assuming the same keys always make the same tree. Shape depends on insertion order, as the example shows.
- Forgetting the recursion cost. The recursive
insertanddeleteuse stack space proportional to h. On a chain of 100,000 keys, Python's default recursion limit (about 1,000) raisesRecursionError. - Ignoring that O(h) is a worst-case bound for one operation. A single search on a deep tree may still be fast if the key sits near the root.
Exercise
A BST built by inserting 10, 20, 30, 40 in that order has height 3. Give the height of the tree built by inserting 20, 10, 40, 30, and say how many comparisons a search for 30 needs in each tree.
Show answer
Inserting 20, 10, 40, 30 puts 20 at the root, 10 as its left child, 40 as its right child, and 30 as the left child of 40. The height is 2. A search for 30 compares with 20, 40, then 30, so 3 comparisons. In the first tree (a chain 10, 20, 30, 40), the search compares with 10, 20, then 30, so 3 comparisons as well. The chain shows its cost on key 40, which needs 4 comparisons there and only 2 in the second tree.
Exercise
Why is the cost of delete still O(h) even though a node with two children requires both a minimum search and a recursive delete?
Show answer
Each of the two steps walks down a single path and never goes deeper than the tree's height, so the total is at most about 2h steps. Constant factors are dropped in Big-O, so the cost is O(h).