Sub topic 13
Cost of BST operations and the role of height
This chapter assumes you can read the BST search, insert and delete code from the previous chapters. It also assumes you know Big-O notation and the standard tree vocabulary. Height is measured in edges, so a single node has height 0 and an empty tree has height -1.
Every operation follows one path
Search, insertion, minimum, maximum and successor lookup all start at the root and move down one child at each step. They never go back up and never visit both children. The work per node is a constant number of comparisons and pointer moves. So the cost is proportional to the number of nodes on the path, which is at most h + 1, where h is the height of the tree.
Deletion has three parts:
- Find the node, which costs at most h steps.
- If the node has two children, walk down to its inorder successor, which costs at most h more steps in total because the walk continues below the node.
- Splice out the successor, which takes constant time.
The total is still O(h). The path never doubles back, so no step is repeated.
| Operation | Cost in terms of height h |
|---|---|
| Search, successful or not | O(h) |
| Minimum, maximum | O(h) |
| Insert | O(h) |
| Delete | O(h) |
| Any full traversal | O(n), independent of h |
The statement "BST operations take O(log n)" is therefore incomplete. The correct statement is that they take O(h), and h is somewhere between log n and n.
Height bounds for n nodes
A binary tree with n nodes has height h satisfying:
- Minimum: h = floor(log2 n), reached by a complete tree. A perfect tree with n = 2^(h+1) - 1 nodes is the extreme case.
- Maximum: h = n - 1, reached by a skewed tree (a chain where every node has one child).
Substituting these bounds gives the cost range for a BST with n keys:
| Tree shape | Height | Cost per operation |
|---|---|---|
| Complete or perfect (best shape) | floor(log2 n) | Θ(log n) |
| Random insertion order (typical) | about c · log n | Θ(log n) expected |
| Skewed (worst shape) | n - 1 | Θ(n) |
Best, average and worst case
The word "case" can refer to two different things, and GATE questions use both.
- Case for a single operation on a fixed tree. The best case is that the key is at the root, which costs O(1). The worst case is that the key is at the deepest level or absent, which costs h + 1 node visits.
- Case over the shape of the tree. The best shape is complete, with h = floor(log2 n). The worst shape is skewed, with h = n - 1.
The worst-case cost for n keys is Θ(n). It occurs when the keys are inserted in sorted order, ascending or descending. Inserting 1, 2, 3, ..., n builds a right chain. Searching for n then visits all n nodes.
The average case depends on the probability model you assume.
- If keys are inserted in a uniformly random permutation, the expected depth of a node is about 2 ln n, which is roughly 1.39 log2 n. The expected height is still Θ(log n). Operations are logarithmic on average.
- If every tree shape were equally likely (a different model), the expected height would be Θ(√n). This is why the phrase "random BST" needs a stated model.
A GATE-style counting fact: of the n! insertion orders of n distinct keys, exactly 2^(n-1) produce a skewed tree. In each such order, the first remaining key inserted must be the smallest or the largest of the remaining keys. That gives two choices at each of the first n - 1 steps, and the last key is forced. Only one of these orders (ascending) gives the right chain, and only one (descending) gives the left chain. The other orders give zigzag chains.
Measuring it in code
The program below builds a BST from sorted keys and from shuffled keys. It uses an iterative insert, because a recursive insert would hit Python's recursion limit on a chain of 500 nodes.
import math
import random
from collections import deque
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
def insert_iter(root, key):
if root is None:
return Node(key)
node = root
while True:
if key < node.key:
if node.left is None:
node.left = Node(key)
break
node = node.left
elif key > node.key:
if node.right is None:
node.right = Node(key)
break
node = node.right
else:
break # duplicate keys are ignored
return root
def height(root):
"""Height in edges; an empty tree has height -1."""
h = -1
level = deque([root] if root else [])
while level:
h += 1
for _ in range(len(level)):
node = level.popleft()
if node.left:
level.append(node.left)
if node.right:
level.append(node.right)
return h
def nodes_visited(root, key):
count = 0
node = root
while node:
count += 1
if node.key == key:
break
node = node.left if key < node.key else node.right
return count
def build(keys):
root = None
for k in keys:
root = insert_iter(root, k)
return root
n = 500
sorted_keys = list(range(1, n + 1))
shuffled_keys = sorted_keys[:]
random.seed(7)
random.shuffle(shuffled_keys)
chain = build(sorted_keys)
random_tree = build(shuffled_keys)
print("best possible height:", math.floor(math.log2(n)))
print("sorted input height: ", height(chain))
print("sorted: nodes visited searching for", n, "=", nodes_visited(chain, n))
print("shuffled input height:", height(random_tree))
print("shuffled: nodes visited searching for", n, "=", nodes_visited(random_tree, n))The first three lines of output are exact: the best possible height is 8, the sorted input gives height 499, and searching for 500 visits 500 nodes. The shuffled height depends on the seed, but it will be a small multiple of 8 and nowhere near 499.
Costs that depend on h in other ways
- Stack space. A recursive search, insert or delete uses O(h) stack frames. On a chain, this is O(n) and can overflow the stack. An iterative version uses O(1) extra space, which is why the code above is iterative.
- Deletion does not rebalance. Repeated deletions and insertions can make a tree taller even when n stays constant.
- Duplicates. The spine's insert code ignores duplicates. If duplicates are stored instead, a long run of equal keys forms a chain, and the height grows with it.
- Traversal. Inorder, preorder and postorder always cost Θ(n). The height affects only the recursion depth, not the running time.
How balancing fixes the worst case
If a tree could be forced to keep h = O(log n) after every insertion and deletion, every operation would cost O(log n) in the worst case. Height-balanced trees such as AVL trees do this by performing rotations, which are local pointer rearrangements that keep the inorder order. The next chapters cover counting and balancing. For this chapter, the key point is that balancing keeps h close to log n, and the BST cost formulas then give O(log n).
Common errors
- Writing "search is O(log n)" for a general BST. The accurate worst case is O(n).
- Mixing up height in edges and in nodes. A skewed tree of n nodes has height n - 1 in edges and n in nodes. Check which one the question uses. The number of comparisons in a worst-case successful search is h + 1 (edge height) and is not equal to h.
- Assuming a BST built from random input is balanced. It is only balanced in expectation, and the shape still varies from run to run.
- Forgetting that building a BST from n keys by repeated insertion costs O(n · h), which is Θ(n²) for sorted input and Θ(n log n) on average for random input.
Exercise
Keys 40, 20, 60, 10, 30, 50, 70 are inserted into an empty BST in that order. What is the height of the tree, and how many nodes are visited in the worst unsuccessful search? Then say what the height would be if the same keys were inserted in ascending order.
Show answer
The tree is perfect: 40 is the root, 20 and 60 are its children, and 10, 30, 50, 70 are the leaves. The height is 2 edges. An unsuccessful search ends at a null child below a leaf, after visiting 3 nodes (h + 1). In ascending order (10, 20, 30, 40, 50, 60, 70) every key is larger than all previous keys, so the tree is a right chain of height 6 = n - 1, and the worst search visits 7 nodes.
Exercise
How many of the 5! = 120 insertion orders of keys 1 to 5 produce a skewed tree of height 4 (left chain, right chain or zigzag)?
Show answer
2^(n-1) = 2^4 = 16. For each of the first four insertions, the inserted key must be the smallest or the largest of the keys not yet inserted. That gives two choices each time, and the last key is forced. Among these 16 orders are 12345 (right chain) and 54321 (left chain).
Exercise
A BST has n = 1000 nodes. Give the minimum and maximum possible height in edges, and explain why delete is O(h) even though it can run a successor search after finding the node.
Show answer
The minimum height is floor(log2 1000) = 9 and the maximum is 999. Delete first walks down to the target node. If the node has two children, it continues down the left spine of the right subtree to the successor and deletes it from there. The path from the root only goes down, so the total number of steps is at most h, plus a constant for the splice. The total cost is O(h).