Objective
Write the four traversals from memory, implement BST search, insert and delete (including the two-child case), explain what height costs and how balanced trees bound it, and know when a trie or a sorted container is the right tool, with the order book as the running example.
Traversals
A binary tree is a root with a left and a right subtree. Recursive traversals differ only in when they visit the node:
- Preorder (node, left, right): copies or serialises a tree; the root comes first.
- Inorder (left, node, right): on a BST this visits keys in sorted order.
- Postorder (left, right, node): children before parents, so it frees a tree, or computes heights and subtree sums.
- Level order: BFS with a queue, one depth at a time.
Each is time; recursion uses stack for height , and level order uses for the widest level.
from collections import deque
class Node:
def __init__(self, key):
self.key, self.left, self.right = key, None, None
def inorder(node):
return inorder(node.left) + [node.key] + inorder(node.right) if node else []
def preorder(node):
return [node.key] + preorder(node.left) + preorder(node.right) if node else []
def level_order(root):
out, q = [], deque([root] if root else [])
while q:
node = q.popleft()
out.append(node.key)
for child in (node.left, node.right):
if child:
q.append(child)
return out
(The list concatenations make these ; pass an output list down for strict . In an interview, also be ready to write inorder iteratively with an explicit stack: push left children until you hit None, pop and visit, then move to the right child.)
Binary search trees
A BST keeps every key in a node's left subtree smaller than the node and every key in its right subtree larger. Search walks down, going left or right by comparison: . Insert searches and attaches a new leaf where the search fell off. Delete has three cases:
- A leaf: remove it.
- One child: splice the child into the node's place.
- Two children: copy in the inorder successor (the leftmost node of the right subtree, which has no left child), then delete the successor from the right subtree, which is case 1 or 2.
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
elif key > root.key:
root.right = insert(root.right, key)
return root # duplicates ignored
def delete(root, key):
if root is None:
return None
if key < root.key:
root.left = delete(root.left, key)
elif key > root.key:
root.right = delete(root.right, key)
else:
if root.left is None:
return root.right # cases 1 and 2
if root.right is None:
return root.left
succ = root.right # case 3: smallest key on the right
while succ.left:
succ = succ.left
root.key = succ.key
root.right = delete(root.right, succ.key)
return root
Validating a BST is a favourite trap. Checking only that each child is on the correct side of its parent is wrong: the tree (left right ), right passes that test, yet 12 sits in the left subtree of 10. Pass the allowed interval down instead: the left child of a node with key must lie in and the right child in .
Height is everything
Every operation costs . Inserting keys in random order gives an average node depth of ; for that is about 11.0, and a simulation of 200 random trees gave average depth 10.98 and average height about 21. Inserting sorted keys, which is what a stream of rising prices or timestamps produces, builds a path of height , and every operation becomes .
Balanced trees restore worst case by rotating after updates:
- AVL trees keep the subtree heights at every node within 1: height at most about .
- Red–black trees colour nodes so no root-to-leaf path is more than twice as long as another: height at most . C++'s
std::mapandstd::setand Java'sTreeMapare red–black trees. - B-trees store many keys per node, so a lookup touches nodes; databases and file systems use them because each node is one disk or cache-friendly block.
Interviewers rarely want rotations coded; they want you to name the guarantee and know the library structure that provides it. Python's standard library has no balanced tree: use bisect on a sorted list (search , insert but a fast memory shift), a heap if you only need the minimum, or the third-party sortedcontainers.SortedList.
Worked example
traversals and a two-child delete
Insert into an empty BST. Give the preorder, inorder and level-order traversals, then delete 50 and give the new preorder.
Show solutionHide solution
The tree has 50 at the root; 30 (children 20, 40) on the left; 70 (children 60, 80) on the right; and 65 is the right child of 60.
- Preorder: .
- Inorder: , sorted as promised.
- Level order: (which here matches the insertion order, because each level was filled before the next began).
Delete 50. It has two children, so find its inorder successor: go right to 70, then left as far as possible, to 60. Copy 60 into the root and delete 60 from the right subtree; 60 has only a right child, 65, which takes its place under 70. The new preorder is and the inorder is still sorted: . The code above prints exactly these lists.
Lowest common ancestor
The LCA of two nodes is the deepest node that has both as descendants (a node counts as its own descendant).
- In a BST, walk from the root: if both keys are smaller go left, if both are larger go right, otherwise the current node splits them and is the LCA. , no recursion needed.
- In a general binary tree, recurse: return the node if it is
Noneor one of the targets; otherwise ask both subtrees. If both return something, this node is the LCA; else pass up whichever is non-empty. .
def lca_bst(root, a, b):
node = root
while node:
if a < node.key and b < node.key:
node = node.left
elif a > node.key and b > node.key:
node = node.right
else:
return node.key
def lca(node, a, b): # any binary tree; assumes both are present
if node is None or node.key in (a, b):
return node
left, right = lca(node.left, a, b), lca(node.right, a, b)
if left and right:
return node
return left or right
On the tree from the worked example (before the deletion): the LCA of 20 and 40 is 30, of 65 and 80 is 70, of 20 and 65 is 50, and of 60 and 65 is 60 itself. State the assumption that both keys are present; if they might not be, the general version needs to report whether each was found.
Tries
A trie stores strings character by character, so all keys with a common prefix share a path. Insert and lookup cost for a key of length , independent of how many keys are stored, and prefix queries ("every ticker starting with AM") come for free:
class Trie:
def __init__(self):
self.root = {}
def insert(self, word):
node = self.root
for ch in word:
node = node.setdefault(ch, {})
node["*"] = True # end-of-word marker
def starts_with(self, prefix):
node = self.root
for ch in prefix:
if ch not in node:
return []
node = node[ch]
out, stack = [], [(node, prefix)]
while stack:
node, word = stack.pop()
if "*" in node:
out.append(word)
for ch, child in node.items():
if ch != "*":
stack.append((child, word + ch))
return sorted(out)
t = Trie()
for s in ["AAPL", "AMD", "AMZN", "AMAT", "MSFT"]:
t.insert(s)
print(t.starts_with("AM")) # ['AMAT', 'AMD', 'AMZN']
The trade-off is memory: one node per distinct prefix. A hash set answers exact lookups more cheaply; the trie wins when you need prefixes or ordered enumeration of strings.
Sorted containers under an order book
Each side of a book needs, per price level: the best price, insert a new level, remove an emptied level (often not the best one, after a cancel), iterate levels in price order to match or to publish depth, and range queries such as "total size within 3 ticks of the best".
| Container | Best price | Add/remove level | Ordered walk, range query |
|---|---|---|---|
| Binary heap | push ; arbitrary removal needs lazy deletion | no | |
| Sorted array + binary search | shift, small constant | yes, | |
Balanced BST (std::map) | with a cached end, else | yes, | |
| Array indexed by tick | amortised with a best-level pointer | yes, scan the ticks |
The heap from the earlier order-book lesson is fine for "best price only", but depth queries and cancels of deep levels favour an ordered structure. In practice most activity is within a few ticks of the touch and is small, so a sorted array (best price at the end, so updates near the touch shift few elements) or a tick-indexed array often beats a tree on real hardware.
from bisect import bisect_left, bisect_right, insort
prices, qty = [], {} # ask levels in integer ticks (best first, for clarity)
def add(px, q):
if px not in qty:
insort(prices, px)
qty[px] = 0
qty[px] += q
for px, q in [(10001, 300), (10003, 200), (10002, 500), (10007, 100), (10001, 200)]:
add(px, q)
best = prices[0]
window = prices[bisect_left(prices, best) : bisect_right(prices, best + 3)]
print(prices, sum(qty[p] for p in window)) # [10001, 10002, 10003, 10007] 1200
Within 3 ticks of the best ask (10001 to 10004) sit . Storing prices as integer ticks rather than floats keeps the comparisons exact. When the question is about overlapping intervals (which halts, quotes or sessions contain time ?), the answer is an interval tree: a BST keyed on interval start, with each node also storing the maximum end point in its subtree so whole subtrees can be skipped.
Knowledge check
Prices 101, 102, 103, ..., 200 are inserted in that order into a plain (unbalanced) BST. What is its height, and what does a lookup cost?
Knowledge check
A validator checks, at every node, only that the left child's key is smaller and the right child's key is larger. On which tree does it wrongly return True?
Knowledge check
Which traversal would you use to free every node of a tree, or to compute each subtree's total quantity?
Key takeaways
- Preorder, inorder, postorder and level order are all ; inorder on a BST is sorted, postorder computes subtree aggregates.
- BST operations cost ; delete with two children copies the inorder successor. Validate with bounds, not parent–child comparisons.
- Random insertion gives depth about , sorted insertion gives a path; AVL, red–black and B-trees guarantee , and
std::mapis a red–black tree. - LCA is a single walk in a BST and an recursion in a general tree; tries give prefix queries at a memory cost.
- For order-book levels, choose by operations: heap for best-only, sorted array or tick array when levels are few and near the touch, balanced tree for general ordered updates.
Practice problems
Finished reading?
Answer the 3 knowledge checks to complete this lesson (0 done).