Trees and Binary Search Trees Questions
Tree data structures as tested in coding interviews: binary trees, binary search trees, self-balancing trees (AVL insertion and deletion with rotations, a comparison with red-black trees, and alternatives such as treaps, splay trees and scapegoat trees), tries (prefix trees and radix trees), and N-ary, size-augmented and sum-augmented trees such as order-statistic trees. Covers traversal orders (in/pre/post-order, level-order, zigzag, iterative, generator-based and Morris variants), BST search, insertion and deletion invariants including duplicate-key policies, validation, successor and iterator design, range and kth-smallest queries, lowest common ancestor (including parent pointers, binary lifting and repeated queries on a static tree), tree reconstruction from traversals, serialization formats and parsing, converting between trees and sorted lists or linked lists, height, balance, diameter and path-sum recursion, subtree equality and hashing, persistent and snapshot-consistent trees, and how tree shape drives logarithmic versus degenerate performance. Excludes plain linked-list and stack/queue exercises with no tree in them, tree dynamic programming recurrences, general graph traversal, heap mechanics, and on-disk database index design, which are covered elsewhere.
Return all keys of a BST that fall inside [low, high] in sorted order, pruning subtrees that cannot contain answers. What is the cost in terms of the output size k and the height h?
Sample Answer
The idea in plain words
In a binary search tree (BST) every key in a node's left subtree is smaller than the node's key and every key in its right subtree is larger. So at any node you can tell from the node's own key whether a side can hold answers. If node.key <= low, everything on the left is below the range and the left subtree is skipped. If node.key >= high, everything on the right is above the range and the right subtree is skipped. Doing the left part, then the node, then the right part (an inorder walk) emits the keys already sorted, so no sorting step is needed. Heights and depths count edges (empty tree -1, single node 0), and h is the tree height. Keys are assumed distinct; the edge cases below say what changes when equal keys are stored.
The brute force is a full inorder walk that filters: O(n) even when only a few keys match. The pruned walk costs O(h + k) where k is the number of keys returned.
The approach
For each visited node:
- Recurse into the left child only if
low < node.key. - Append
node.keyiflow <= node.key <= high. - Recurse into the right child only if
node.key < high.
Example tree and the query [33, 62]:
50
/ \
30 70
/ \ / \
20 40 60 80
/ \
35 45
Code
import random
class Node:
__slots__ = ("key", "left", "right")
def __init__(self, key):
self.key = key
self.left = self.right = None
def insert(root, key):
if root is None:
return Node(key)
node = root
while True:
if key == node.key:
return root
side = "left" if key < node.key else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, Node(key))
return root
node = child
def range_keys(node, low, high, out, stats, log=None):
"""Append keys in [low, high] to out in sorted order, skipping subtrees that cannot match."""
if node is None:
return
stats["visited"] += 1
go_left = low < node.key # keys in the left subtree are all < node.key
go_right = node.key < high # keys in the right subtree are all > node.key
if log is not None:
log.append(f"visit {node.key}: left {'yes' if go_left else 'skip'}, "
f"{'keep' if low <= node.key <= high else 'drop'}, right {'yes' if go_right else 'skip'}")
if go_left:
range_keys(node.left, low, high, out, stats, log)
if low <= node.key <= high:
out.append(node.key)
if go_right:
range_keys(node.right, low, high, out, stats, log)
def range_keys_iterative(root, low, high):
out, stack, node = [], [], root
while stack or node:
if node:
if node.key < low:
node = node.right # this node and its whole left subtree are below the range
else:
stack.append(node)
node = node.left
else:
node = stack.pop()
if node.key > high:
break # everything still to come is larger
out.append(node.key)
node = node.right
return out
def height(root):
best, stack = -1, [(root, 0)] if root else []
while stack:
node, depth = stack.pop()
best = max(best, depth)
for child in (node.left, node.right):
if child:
stack.append((child, depth + 1))
return best
root = None
for key in (50, 30, 70, 20, 40, 60, 80, 35, 45):
root = insert(root, key)
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
# / \
# 35 45
out, stats, log = [], {"visited": 0}, []
range_keys(root, 33, 62, out, stats, log)
print("\n".join(log))
print("result", out, "visited", stats["visited"], "of 9 nodes")
print("iterative", range_keys_iterative(root, 33, 62))
# visited nodes versus k and h on a random tree of 2000 distinct keys
rng = random.Random(41)
keys = rng.sample(range(100000), 2000)
big = None
for key in keys:
big = insert(big, key)
h = height(big)
ordered = sorted(keys)
print(f"\nn = 2000, height h = {h} (edges)")
print(" low high k visited k + 2*(h+1)")
for low, high in [(40000, 40500), (40000, 45000), (10000, 60000), (0, 99999), (60000, 40000)]:
out, stats = [], {"visited": 0}
range_keys(big, low, high, out, stats)
assert out == [x for x in ordered if low <= x <= high] == range_keys_iterative(big, low, high)
bound = len(out) + 2 * (h + 1)
assert stats["visited"] <= bound
print(f"{low:6d} {high:6d} {len(out):6d} {stats['visited']:8d} {bound:12d}")
# random trees and ranges against a plain filter, including empty and single-node trees
checked = 0
for _ in range(500):
tree, model = None, set()
for _ in range(rng.randint(0, 30)):
value = rng.randint(0, 50)
tree = insert(tree, value); model.add(value)
low, high = rng.randint(-5, 55), rng.randint(-5, 55)
out, stats = [], {"visited": 0}
range_keys(tree, low, high, out, stats)
assert out == [x for x in sorted(model) if low <= x <= high] == range_keys_iterative(tree, low, high)
assert stats["visited"] <= len(out) + 2 * (height(tree) + 1)
checked += 1
print("\nrandom check:", checked, "trees and ranges agree with a plain filter")
# a skewed tree 5000 levels deep: the recursive version runs out of stack, the loop does not
chain = Node(0)
tail = chain
for key in range(1, 5000):
tail.right = Node(key)
tail = tail.right
try:
range_keys(chain, 0, 4999, [], {"visited": 0})
except RecursionError:
print("recursive version on a 5000-deep chain: RecursionError")
print("iterative version on the same chain returns", len(range_keys_iterative(chain, 0, 4999)), "keys")
Output:
visit 50: left yes, keep, right yes
visit 30: left skip, drop, right yes
visit 40: left yes, keep, right yes
visit 35: left yes, keep, right yes
visit 45: left yes, keep, right yes
visit 70: left yes, drop, right skip
visit 60: left yes, keep, right yes
result [35, 40, 45, 50, 60] visited 7 of 9 nodes
iterative [35, 40, 45, 50, 60]
n = 2000, height h = 23 (edges)
low high k visited k + 2*(h+1)
40000 40500 9 22 57
40000 45000 85 101 133
10000 60000 1024 1034 1072
0 99999 2000 2000 2048
60000 40000 0 1 48
random check: 500 trees and ranges agree with a plain filter
recursive version on a 5000-deep chain: RecursionError
iterative version on the same chain returns 5000 keys
Reading the trace
At 30 the left subtree (just 20) is skipped because 30 is not greater than 33, and 30 itself is dropped as too small, but its right subtree can still hold 35 to 45. At 70 the right subtree (80) is skipped because 70 is not below 62, and 70 is dropped as too large. Seven of nine nodes were visited: 20 and 80 were never touched. In the trace lines, "left yes" means the left branch is allowed; at a leaf such as 35 the child is empty, so nothing further is entered or counted.
Why the cost is O(h + k)
Every visited node falls into one of three groups:
- Nodes inside the range: exactly k of them, each visited once.
- Nodes below
low: any such node lies on the search path forlow. Going left from an ancestor requiresancestor.key > low, and going right requiresancestor.key < node.key < low, and these are exactly the decisions a normal BST search forlowmakes. That path has at most h + 1 nodes. - Nodes above
high: by the mirror argument, they lie on the search path forhigh, at most h + 1 nodes.
In plain words: the walk can only reach a node below low by steering toward low. Going left from an ancestor is allowed only if low < ancestor.key, which is the turn a lookup for low takes at that ancestor. Going right to reach a node that is itself below low means the ancestor is below low too, and a lookup for low also turns right there. So a below-range node is only ever reached by the turns of one lookup for low, and the mirror holds for high.
So the visits number at most k + 2(h + 1), which is O(h + k). The table confirms it on a random 2000-key tree (h = 23): every row's visited is under k + 2*(h+1). When low is above high the two descent guards (the tests low < node.key and node.key < high that decide whether to enter the left or right child) cannot both hold, so the walk follows at most one root-to-leaf path (the last table row visits a single node). The recursion uses O(h) stack and the output list holds k keys.
On a balanced tree h is about log n, so the cost is O(log n + k). On a skewed tree (one that leans to a single side so it looks like a linked list) h approaches n and the cost is O(n). Python's default recursion limit is about 1000 frames, so the recursive function fails with RecursionError on the 5000-deep chain at the end of the output. The iterative version keeps its own stack of ancestors (also O(h) space but not limited by Python's frame limit) and returns all 5000 keys.
Checking the proof on the drawn tree
For the query [33, 62], the lookup path for 33 is 50, 30, 40, 35 and the lookup path for 62 is 50, 70, 60. The only visited nodes outside the range are 30 (below 33, on the path for 33) and 70 (above 62, on the path for 62), which is what the proof predicts. The same program also prints the iterative version step by step.
class Node:
__slots__ = ("key", "left", "right")
def __init__(self, key):
self.key = key
self.left = self.right = None
def insert(root, key):
if root is None:
return Node(key)
node = root
while True:
side = "left" if key < node.key else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, Node(key))
return root
node = child
def search_path(root, key):
"""Keys of the nodes a plain BST lookup for `key` compares against."""
path, node = [], root
while node:
path.append(node.key)
if key == node.key:
break
node = node.left if key < node.key else node.right
return path
def visited_keys(node, low, high, out):
if node is None:
return
out.append(node.key)
if low < node.key:
visited_keys(node.left, low, high, out)
if node.key < high:
visited_keys(node.right, low, high, out)
root = None
for key in (50, 30, 70, 20, 40, 60, 80, 35, 45):
root = insert(root, key)
low, high = 33, 62
path_low, path_high = search_path(root, low), search_path(root, high)
print("lookup path for", low, ":", path_low)
print("lookup path for", high, ":", path_high)
seen = []
visited_keys(root, low, high, seen)
inside = [k for k in seen if low <= k <= high]
outside = [k for k in seen if k not in inside]
print("visited:", sorted(seen))
print("inside the range:", sorted(inside), "| outside:", sorted(outside))
print("outside nodes below low on the low path:", [k for k in outside if k < low and k in path_low])
print("outside nodes above high on the high path:", [k for k in outside if k > high and k in path_high])
print("\niterative walk, step by step")
stack, node, out = [], root, []
while stack or node:
if node:
if node.key < low:
print(f"at {node.key}: below {low}, skip it and its left subtree, go right")
node = node.right
else:
print(f"at {node.key}: push, go left; stack {[n.key for n in stack] + [node.key]}")
stack.append(node)
node = node.left
else:
node = stack.pop()
if node.key > high:
print(f"pop {node.key}: above {high}, stop")
break
out.append(node.key)
print(f"pop {node.key}: keep; result {out}")
node = node.right
Output:
lookup path for 33 : [50, 30, 40, 35]
lookup path for 62 : [50, 70, 60]
visited: [30, 35, 40, 45, 50, 60, 70]
inside the range: [35, 40, 45, 50, 60] | outside: [30, 70]
outside nodes below low on the low path: [30]
outside nodes above high on the high path: [70]
iterative walk, step by step
at 50: push, go left; stack [50]
at 30: below 33, skip it and its left subtree, go right
at 40: push, go left; stack [50, 40]
at 35: push, go left; stack [50, 40, 35]
pop 35: keep; result [35]
pop 40: keep; result [35, 40]
at 45: push, go left; stack [50, 45]
pop 45: keep; result [35, 40, 45]
pop 50: keep; result [35, 40, 45, 50]
at 70: push, go left; stack [70]
at 60: push, go left; stack [70, 60]
pop 60: keep; result [35, 40, 45, 50, 60]
pop 70: above 62, stop
Reading the iterative trace: range_keys_iterative is the same walk with its own stack. A node below low (30) is skipped together with its left subtree, and only its right child is tried. Any other node is pushed and the walk dives left. A popped node is kept, and then its right child is handled the same way. The first popped node above high (70) ends the loop, because inorder order means every key still to come is larger.
Edge cases and common mistakes
- Empty tree: returns an empty list. low > high: returns an empty list, and the walk follows at most one root-to-leaf path because the two descent guards cannot both hold.
- Inclusive bounds: keys equal to low or high are kept. With distinct keys, using
<=instead of<in the descent guards is harmless for correctness (it only visits extra nodes) but adds visits; using<where you meant<=in the keep test drops boundary keys. - Appending the node before the left recursion produces preorder (node first, then left, then right), not sorted order.
- Pruning on the wrong side, for example skipping the right subtree when the node is below low. A node below the range still has a right subtree that can reach into it (30 in the trace).
- A BST that stores duplicate keys: the code above assumes distinct keys (the
insertin the first program ignores a repeat, and theinsertin the checking program sends an equal key to the right). When equal keys are stored they sit on the side the insert rule picks, and the guard facing that side must be non-strict. If equal keys go left, usego_left = low <= node.key; if they go right, usego_right = node.key <= high. With both guards strict, a stored copy ofloworhighcan be skipped and missing from the result.
Running the code
Save as range_bst.py and run python3 range_bst.py (Python 3.12, standard library only). The program in the checking section is self-contained: save it as search_paths.py and run it the same way.
What are the time and space costs of preorder, inorder, postorder and level-order traversal? Separate the recursion stack from explicit stack or queue usage, and show how the numbers change for balanced versus degenerate trees.
Sample Answer
Direct answer
The three numbers to remember: time O(n) for every traversal, space O(h) for the depth-first ones, space O(w) for level-order.
All four traversals (preorder, inorder, postorder, level-order) take O(n) time: each node is visited once, pushed once and popped once. They differ in space. The three depth-first orders hold a path from the root: O(h) for h the tree height, whether that path lives in recursion call frames or in an explicit stack. Level-order holds a frontier (the nodes discovered but not yet processed: the unfinished part of the current level plus the children already queued for the next, so at most two neighbouring levels) in a queue: O(w) for w the widest level (the most nodes on any single level). On a balanced tree h is about log2(n) (10 for 1023 nodes) while w is about n / 2 (512). On a degenerate (skewed) tree, one where every node has at most one child so the tree is a chain, h = n, so recursion costs O(n) call frames, while the explicit stack or queue can be as small as 1 or as large as n depending on the order and which way the tree leans.
Height convention: number of nodes on the longest root-to-leaf path (empty tree = 0); counting edges instead gives one less for every height here. Preorder visits node, left, right; inorder visits left, node, right; postorder visits left, right, node; level-order goes one level at a time. A call frame is the block of memory one active function call occupies on the call stack.
Recursion stack versus explicit stack or queue
- Recursion stack: the call stack of the language. Memory use is the deepest nesting of calls, which equals h for every DFS order. It is invisible in the code but real, and it has a fixed cap: CPython allows about 1000 frames by default.
- Explicit stack (iterative DFS): a list or stack you manage, living on the heap. Its peak size depends on the order: preorder pushes pending right siblings, inorder pushes the whole left spine, postorder keeps all ancestors of the current node. Each is O(h) at worst, but the actual peak differs by shape (see the table).
- Queue (level-order): a
collections.deque. Its peak size is set by the widest level: at most two neighbouring levels are in the queue at once, so it is O(w). On the perfect tree below the peak equals the bottom level, 512. A Pythonlistwithpop(0)would make each removal O(n) and the traversal O(n^2).
Measured, with the code that produced it
The program counts node visits, the deepest call nesting for the recursive versions, and pushes plus peak size for the iterative versions, on a perfect tree and on two degenerate trees (all nodes on the left, and all on the right).
from collections import deque
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val, self.left, self.right = val, None, None
def perfect(levels):
root = Node(0); level, c = [root], 1
for _ in range(levels - 1):
nxt = []
for n in level:
n.left, n.right = Node(c), Node(c + 1); c += 2
nxt += [n.left, n.right]
level = nxt
return root
def chain(n, side):
root = cur = Node(0)
for v in range(1, n):
child = Node(v)
setattr(cur, side, child)
cur = child
return root
# ---- recursive versions: count node visits and the deepest nesting of calls (frames) ----
def recursive(root, order):
stats = {"visits": 0, "frames": 0, "max_frames": 0}
def go(node):
stats["frames"] += 1
stats["max_frames"] = max(stats["max_frames"], stats["frames"])
if order == "pre": stats["visits"] += 1
if node.left: go(node.left)
if order == "in": stats["visits"] += 1
if node.right: go(node.right)
if order == "post": stats["visits"] += 1
stats["frames"] -= 1
go(root)
return stats["visits"], stats["max_frames"]
# ---- iterative versions: count pushes and the largest size of the explicit stack / queue ----
def preorder_iter(root):
stack, peak, pushes = [root], 1, 1
while stack:
node = stack.pop()
for c in (node.right, node.left):
if c:
stack.append(c); pushes += 1
peak = max(peak, len(stack))
return pushes, peak
def inorder_iter(root):
stack, cur, peak, pushes = [], root, 0, 0
while cur or stack:
while cur:
stack.append(cur); pushes += 1
cur = cur.left
peak = max(peak, len(stack))
cur = stack.pop().right
return pushes, peak
def postorder_iter(root):
stack, cur, last, peak, pushes = [], root, None, 0, 0
while cur or stack:
while cur:
stack.append(cur); pushes += 1
cur = cur.left
peak = max(peak, len(stack))
top = stack[-1]
if top.right and top.right is not last:
cur = top.right # right subtree not done yet
else:
last = stack.pop() # both subtrees done: visit
return pushes, peak
def level_iter(root):
queue, peak, pushes = deque([root]), 1, 1
while queue:
node = queue.popleft()
for c in (node.left, node.right):
if c:
queue.append(c); pushes += 1
peak = max(peak, len(queue))
return pushes, peak
shapes = [("perfect (n=1023, h=10)", perfect(10)),
("left chain (n=1000, h=1000)", chain(1000, "left")),
("right chain (n=1000, h=1000)", chain(1000, "right"))]
import sys
sys.setrecursionlimit(1300) # the 1000-node chains need ~1000 frames plus the caller's frames
for name, t in shapes:
print(name)
for order in ("pre", "in", "post"):
visits, frames = recursive(t, order)
print(f" {order + 'order':10} recursive: visits={visits:5} max call frames={frames:5}")
for label, fn in [("preorder", preorder_iter), ("inorder", inorder_iter),
("postorder", postorder_iter), ("level-order", level_iter)]:
pushes, peak = fn(t)
print(f" {label:11} explicit: pushes={pushes:5} peak stack/queue size={peak:5}")
Output:
perfect (n=1023, h=10)
preorder recursive: visits= 1023 max call frames= 10
inorder recursive: visits= 1023 max call frames= 10
postorder recursive: visits= 1023 max call frames= 10
preorder explicit: pushes= 1023 peak stack/queue size= 10
inorder explicit: pushes= 1023 peak stack/queue size= 10
postorder explicit: pushes= 1023 peak stack/queue size= 10
level-order explicit: pushes= 1023 peak stack/queue size= 512
left chain (n=1000, h=1000)
preorder recursive: visits= 1000 max call frames= 1000
inorder recursive: visits= 1000 max call frames= 1000
postorder recursive: visits= 1000 max call frames= 1000
preorder explicit: pushes= 1000 peak stack/queue size= 1
inorder explicit: pushes= 1000 peak stack/queue size= 1000
postorder explicit: pushes= 1000 peak stack/queue size= 1000
level-order explicit: pushes= 1000 peak stack/queue size= 1
right chain (n=1000, h=1000)
preorder recursive: visits= 1000 max call frames= 1000
inorder recursive: visits= 1000 max call frames= 1000
postorder recursive: visits= 1000 max call frames= 1000
preorder explicit: pushes= 1000 peak stack/queue size= 1
inorder explicit: pushes= 1000 peak stack/queue size= 1
postorder explicit: pushes= 1000 peak stack/queue size= 1000
level-order explicit: pushes= 1000 peak stack/queue size= 1
Reading the numbers
- Time: every row shows visits (or pushes) equal to n: 1023 for the perfect tree, 1000 for each chain. Nothing is visited twice, so each traversal is O(n) in every shape.
- Perfect tree: recursion needs 10 frames; the explicit stacks peak at 10; the level-order queue peaks at 512, the width of the bottom level. Depth-first is far cheaper in memory here.
- Left chain: recursion needs 1000 frames. Explicit inorder and postorder stacks hold 1000 entries (the whole left spine / all ancestors). The explicit preorder stack holds 1 entry, because a chain has no pending right siblings. The level-order queue holds 1.
- Right chain: recursion still needs 1000 frames. Explicit inorder drops to 1, because each node is popped immediately and its right child is next; postorder still holds 1000, because every ancestor must wait for its right subtree to finish.
- The recursive counts were obtained after raising the recursion limit to 1300, because with the default limit of 1000 the 1000-node chains do not fit (the program's own call frames plus 1000 levels exceed it).
The iterative postorder, in plain words and on a tiny tree
Postorder is the hard one to write with a stack, because a node must be visited only after both children, yet the stack hands the node back to you twice: once when you come back up from the left subtree, and once after the right. The idea: keep every ancestor of the current position on the stack. Look at the node on top. If it has a right child that has not been visited yet, go into that right subtree. Otherwise both sides are finished, so pop and visit it. The variable last is the node visited most recently, and top.right is not last is the test "the right subtree is not done yet": when the walk returns from a right subtree, the node it just finished is exactly the top node's right child.
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def postorder_steps(root):
"""Iterative postorder. `last` is the node visited most recently."""
stack, cur, last, order, peak = [], root, None, [], 0
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
peak = max(peak, len(stack))
top = stack[-1]
if top.right and top.right is not last:
cur = top.right
action = f"right subtree of {top.val} not done, go to {top.right.val}"
else:
last = stack.pop()
order.append(last.val)
action = f"visit {last.val}"
print(f" stack={[n.val for n in stack]} last={last.val if last else None} {action}")
return order, peak
def inorder_peak(root):
stack, cur, peak = [], root, 0
while cur or stack:
while cur:
stack.append(cur)
cur = cur.left
peak = max(peak, len(stack))
cur = stack.pop().right
return peak
print("postorder on root 1, left 2, right 3")
order, peak = postorder_steps(Node(1, Node(2), Node(3)))
print(" order:", order, "peak stack:", peak)
left3 = Node(1, Node(2, Node(3)))
right3 = Node(1, None, Node(2, None, Node(3)))
print("chain of 3 leaning left, postorder")
print(" order:", postorder_steps(left3)[0])
print("chain of 3 leaning right, postorder")
print(" order:", postorder_steps(right3)[0])
print("inorder peak stack, left-leaning chain of 3:", inorder_peak(left3))
print("inorder peak stack, right-leaning chain of 3:", inorder_peak(right3))
It prints (the stack is shown after each step):
postorder on root 1, left 2, right 3
stack=[1] last=2 visit 2
stack=[1] last=2 right subtree of 1 not done, go to 3
stack=[1] last=3 visit 3
stack=[] last=1 visit 1
order: [2, 3, 1] peak stack: 2
chain of 3 leaning left, postorder
stack=[1, 2] last=3 visit 3
stack=[1] last=2 visit 2
stack=[] last=1 visit 1
order: [3, 2, 1]
chain of 3 leaning right, postorder
stack=[1] last=None right subtree of 1 not done, go to 2
stack=[1, 2] last=None right subtree of 2 not done, go to 3
stack=[1, 2] last=3 visit 3
stack=[1] last=2 visit 2
stack=[] last=1 visit 1
order: [3, 2, 1]
inorder peak stack, left-leaning chain of 3: 3
inorder peak stack, right-leaning chain of 3: 1
On root 1 with children 2 and 3, node 2 is visited first. Then the top is 1, whose right child 3 is not last, so the walk goes into 3. After 3 is visited, last is 3, which is 1's right child, so 1 is popped and visited: [2, 3, 1]. On the chain leaning left, every node has only a left child, so the descent pushes the whole chain before anything is visited and the stack holds the ancestors: 2 entries (1 and 2) are waiting when 3 is visited, matching the 1000 (all the ancestors) in the measured left chain. On the chain leaning right, node 1 stays on the stack while the walk goes into 2, and 2 stays while it goes into 3, so the postorder stack also grows to the depth, which is why the measured postorder peak is 1000 on both chains. Inorder differs on the two chains: leaning left it has to push the whole left spine before the first visit (peak 3 here), while leaning right it pops each node and moves straight to its right child (peak 1 here), the same pattern as the 1000 versus 1 in the measured table.
Summary table (n nodes, height h, widest level w)
| Traversal | Time | Recursive space | Explicit stack/queue space | Balanced tree | Degenerate tree |
|---|---|---|---|---|---|
| Preorder | O(n) | O(h) frames | O(h) worst | O(log n) | O(n) frames; explicit stack can be O(1) |
| Inorder | O(n) | O(h) frames | O(h) worst | O(log n) | O(n) frames; explicit O(n) left-leaning, O(1) right-leaning |
| Postorder | O(n) | O(h) frames | O(h) worst | O(log n) | O(n) frames; explicit O(n) |
| Level-order | O(n) | not recursive | O(w) queue | O(n) (about n / 2) | O(1) on a chain |
Morris traversal visits in inorder or preorder with O(1) extra space by temporarily re-pointing links inside the tree (it aims a node's empty right link back at an ancestor, so the walk can climb back without a stack) and restoring them; it runs in O(n) time overall but changes the tree while it runs, so it is unsafe under concurrent readers.
Common mistakes
- Quoting "O(log n) space for DFS" without the condition "if the tree is balanced": the true bound is O(h).
- Counting only the explicit stack and forgetting recursion frames in the recursive version, or the reverse.
- Claiming level-order is "O(1) extra space" or "uses less memory than DFS" in general. On the perfect tree it used 512 entries against 10.
- Using
list.pop(0)as the queue. - Treating the recursion limit as an implementation detail: at h around 1000, a recursive CPython traversal fails.
Running the code
python3 traversal_costs_demo.py
Standard library only (Python 3.12).
Flatten a binary tree into a linked list in place, following preorder, so each node's right child is the next node and left is null. What is the O(n) time, O(h) space version, and can you do it in O(1) extra space?
Sample Answer
The idea in plain words
Preorder visits a node, then its left subtree, then its right subtree. "Flatten in place" means rewiring the existing nodes so that following right pointers from the root visits the nodes in that preorder, with every left set to None. No new nodes are created. Heights count edges (empty tree -1, single node 0) and h is the tree height.
Brute force. Collect the preorder in a list, then relink the nodes from the list: O(n) time and O(n) extra space. The question asks for O(h) extra space, then O(1).
The example tree and its target:
1 1 -> 2 -> 3 -> 4 -> 5 -> 6
/ \ (each arrow is a right pointer,
2 5 every left pointer is None)
/ \ \
3 4 6
Version 1: O(n) time, O(h) space
Walk the tree in reverse preorder (right subtree, then left subtree, then the node) and keep a variable prev holding the node processed just before. When the node itself is handled, set node.right = prev and node.left = None, then prev = node. Reverse preorder is the mirror image of postorder (postorder goes left subtree, right subtree, node), and it produces the nodes in exactly the opposite sequence from preorder: for the example tree its visit order is 6, 5, 4, 3, 2, 1, against the preorder 1, 2, 3, 4, 5, 6. Because it handles the last preorder node first, each node ends up pointing at the one that follows it in preorder: when 5 is handled, prev is 6, so 5 points to 6; when 2 is handled, prev is 3, so 2 points to 3. The traced run is in the next section. The recursion depth is the tree height. flatten_stack does the same job with an explicit stack: pop a node, link the previously popped node's right to it, push the node's right child and then its left child (so the left comes off first).
Version 2: O(n) time, O(1) extra space
Walk down the future list with a pointer cur. If cur has a left subtree, the part of the preorder that follows cur is that left subtree, and the old right subtree must come after the left subtree's last node. That last node is the rightmost node of the left subtree (the end of its chain of right pointers). So:
- Find
tail, the rightmost node ofcur.left. - Attach the old right subtree after it:
tail.right = cur.right. - Move the left subtree to the right:
cur.right = cur.left,cur.left = None. - Step to
cur.rightand repeat.
No stack is needed because the structure itself remembers where to continue. The scans for tail look like a nested loop but cost O(n) in total. A scan starts by going left once and then follows only right pointers. After the splice, every node it walked over is reached from the root by right pointers alone, and the splice never creates a new left edge. A later scan always begins by going down a left edge, so it cannot pass through a node that is reachable by right pointers only. Hence each node is walked over by at most one scan, and the scan steps total at most n. The next section prints the scan steps for random trees and for a worst-case shape.
Code
import random
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val = val
self.left = self.right = None
def preorder(root):
out, stack = [], [root] if root else []
while stack:
node = stack.pop()
out.append(node.val)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return out
def flatten_recursive(root):
"""O(n) time, O(h) space: visit right, then left, then the node; each node points at the previous one."""
prev = None
def go(node):
nonlocal prev
if node is None:
return
go(node.right)
go(node.left)
node.right, node.left = prev, None
prev = node
go(root)
return root
def flatten_stack(root):
"""O(n) time, O(h) space with an explicit stack (no recursion limit)."""
stack, prev = [root] if root else [], None
while stack:
node = stack.pop()
if prev:
prev.right, prev.left = node, None
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
prev = node
return root
def flatten_constant_space(root, log=None, scans=None):
"""O(n) time, O(1) space: splice the left subtree between a node and its right subtree."""
cur = root
while cur:
if cur.left:
tail = cur.left
while tail.right: # rightmost node of the left subtree
tail = tail.right
if scans is not None:
scans[0] += 1
tail.right = cur.right # old right subtree hangs after that node
cur.right, cur.left = cur.left, None # left subtree becomes the right child
if log is not None:
log.append(f"cur={cur.val}: tail={tail.val}; right chain from root now {chain(root)}")
cur = cur.right
return root
def chain(root):
out = []
while root:
out.append(root.val); root = root.right
return out
def is_flat(root, expected):
out = []
while root:
assert root.left is None
out.append(root.val); root = root.right
return out == expected
def random_tree(seed, n):
rng = random.Random(seed)
if n == 0:
return None
root = Node(0)
slots = [(root, "left"), (root, "right")]
for v in range(1, n):
i = rng.randrange(len(slots))
slots[i], slots[-1] = slots[-1], slots[i]
parent, side = slots.pop()
child = Node(v)
setattr(parent, side, child)
slots += [(child, "left"), (child, "right")]
return root
# 1
# / \
# 2 5
# / \ \
# 3 4 6
def example():
nodes = {v: Node(v) for v in range(1, 7)}
nodes[1].left, nodes[1].right = nodes[2], nodes[5]
nodes[2].left, nodes[2].right = nodes[3], nodes[4]
nodes[5].right = nodes[6]
return nodes[1]
print("preorder before:", preorder(example()))
log = []
flatten_constant_space(example(), log)
print("\n".join(log))
for flatten in (flatten_recursive, flatten_stack, flatten_constant_space):
tree = flatten(example())
print(f"{flatten.__name__:24s}", chain(tree), "| every left is None:", is_flat(tree, [1, 2, 3, 4, 5, 6]))
worst_scan = 0
for seed in range(400):
n = random.Random(seed).randint(0, 60)
expected = preorder(random_tree(seed, n))
for flatten in (flatten_recursive, flatten_stack, flatten_constant_space):
assert is_flat(flatten(random_tree(seed, n)), expected)
scans = [0]
flatten_constant_space(random_tree(seed, n), scans=scans)
assert scans[0] <= n
print("random check: all three versions match the preorder of 400 random trees; extra scan steps never exceeded n")
def left_chain(n):
root = Node(0)
node = root
for v in range(1, n):
node.left = Node(v)
node = node.left
return root
try:
flatten_recursive(left_chain(5000))
except RecursionError:
print("recursive version on a 5000-deep left chain: RecursionError")
for flatten in (flatten_stack, flatten_constant_space):
print(f"{flatten.__name__} on the same chain:", len(chain(flatten(left_chain(5000)))), "nodes in order:",
chain(flatten(left_chain(5000))) == list(range(5000)))
Output:
preorder before: [1, 2, 3, 4, 5, 6]
cur=1: tail=4; right chain from root now [1, 2, 4, 5, 6]
cur=2: tail=3; right chain from root now [1, 2, 3, 4, 5, 6]
flatten_recursive [1, 2, 3, 4, 5, 6] | every left is None: True
flatten_stack [1, 2, 3, 4, 5, 6] | every left is None: True
flatten_constant_space [1, 2, 3, 4, 5, 6] | every left is None: True
random check: all three versions match the preorder of 400 random trees; extra scan steps never exceeded n
recursive version on a 5000-deep left chain: RecursionError
flatten_stack on the same chain: 5000 nodes in order: True
flatten_constant_space on the same chain: 5000 nodes in order: True
Tracing Version 1 and counting the tail scans
flatten_recursive handles the nodes in the order 6, 5, 4, 3, 2, 1 on the example tree. The traced run below prints, for each handled node, what its right becomes (the node handled just before it), and then counts the steps the Version 2 scans take on random trees and on a tree built so that one scan walks almost every node:
import random
class Node:
__slots__ = ("val", "left", "right")
def __init__(self, val):
self.val = val
self.left = self.right = None
def example():
nodes = {v: Node(v) for v in range(1, 7)}
nodes[1].left, nodes[1].right = nodes[2], nodes[5]
nodes[2].left, nodes[2].right = nodes[3], nodes[4]
nodes[5].right = nodes[6]
return nodes[1]
def chain(root):
out = []
while root:
out.append(root.val)
root = root.right
return out
def flatten_recursive_traced(root):
prev = None
def go(node):
nonlocal prev
if node is None:
return
go(node.right)
go(node.left)
node.right, node.left = prev, None
print(f"handle {node.val}: right becomes {prev.val if prev else None}")
prev = node
go(root)
return root
tree = flatten_recursive_traced(example())
print("chain from root:", chain(tree))
# Total steps spent walking down to the rightmost node of a left subtree.
def flatten_counting(root):
scans, cur = 0, root
while cur:
if cur.left:
tail = cur.left
while tail.right:
tail = tail.right
scans += 1
tail.right = cur.right
cur.right, cur.left = cur.left, None
cur = cur.right
return scans
def random_tree(seed, n):
rng = random.Random(seed)
root = Node(0)
slots = [(root, "left"), (root, "right")]
for v in range(1, n):
i = rng.randrange(len(slots))
slots[i], slots[-1] = slots[-1], slots[i]
parent, side = slots.pop()
child = Node(v)
setattr(parent, side, child)
slots += [(child, "left"), (child, "right")]
return root
def left_with_long_right_spine(n):
root = Node(0)
root.left = Node(1)
tail = root.left
for v in range(2, n):
tail.right = Node(v)
tail = tail.right
return root
print("random trees, n = 1000, scan steps:", [flatten_counting(random_tree(s, 1000)) for s in range(5)])
print("root whose left child starts a right spine of 999 nodes: n = 1000, scan steps:",
flatten_counting(left_with_long_right_spine(1000)))
Output:
handle 6: right becomes None
handle 5: right becomes 6
handle 4: right becomes 5
handle 3: right becomes 4
handle 2: right becomes 3
handle 1: right becomes 2
chain from root: [1, 2, 3, 4, 5, 6]
random trees, n = 1000, scan steps: [494, 495, 489, 494, 496]
root whose left child starts a right spine of 999 nodes: n = 1000, scan steps: 998
Every line handle X: right becomes Y is the single link X -> Y, and Y is the node that follows X in preorder. Node 6 is handled first, so it becomes the end of the list (right is None). The chain from the root then reads 1, 2, 3, 4, 5, 6. The scan counts stay below n = 1000 in every case: 489 to 496 on the five random trees shown and 998 when one left subtree is a long right spine, the shape that makes a single scan as long as possible. Total scan work cannot exceed n because no node is scanned twice.
flatten_stack follows the same link rule in the forward direction: it pops nodes in preorder (1, 2, 3, 4, 5, 6 here) because it pushes the right child before the left child, so the left child is popped first. Each popped node becomes the right of the node popped before it.
Reading the trace
At cur = 1 the left subtree is rooted at 2 and its rightmost node is 4, so 4.right becomes 5 (the old right subtree) and 1.right becomes 2. From the root the right chain is now 1, 2, 4, 5, 6, which is correct except that node 2 still has its own left child 3. At cur = 2 the rightmost node of its left subtree (just 3) gets 3.right = 4, giving 1, 2, 3, 4, 5, 6. Nodes 3, 4, 5 and 6 have no left child, so nothing more changes.
Complexity
| Version | Time | Extra space |
|---|---|---|
flatten_recursive | O(n) | O(h) recursion |
flatten_stack | O(n) | O(h) stack |
flatten_constant_space | O(n) | O(1) |
On a balanced tree h is about log n; on a skewed tree h is n - 1. Python's default recursion limit is about 1000 frames, so flatten_recursive raises RecursionError on the 5000-deep left chain shown at the end of the output, while the other two succeed.
Edge cases and common mistakes
- Empty tree: all three return
None. Single node: unchanged. - Node with only a left child:
tail.right = cur.rightattachesNone, which is right. - Node with only a right child: the loop just moves on.
- Setting
cur.right = cur.leftbefore saving the old right subtree overwrites the only link to it, so the tail then links back into the list (on the example tree node 3 ends up pointing at itself) and nodes 5 and 6 are lost. Attach the old right subtree totailfirst. - Forgetting
cur.left = Noneleaves the old left pointer in place, so the right chain is still correct but the same nodes are reachable by two paths, and any later tree traversal visits them more than once. - In the recursive version, visiting the left subtree before the right subtree with the same
prevrule links the nodes in the wrong order: on the example tree the right chain reads 1, 5, 6, 2, 4, 3. Visit the right subtree first (reverse preorder), which avoids needing to find a tail. - Skipping the scan for the rightmost node and attaching the right subtree to
cur.leftdirectly overwrites the right child the left subtree already has, so the nodes behind it are lost whenever the left subtree has a right chain (on the example tree the chain reads 1, 2, 3, 5, 6 and node 4 disappears).
Running the code
Save as flatten_tree.py and run python3 flatten_tree.py (Python 3.12, standard library only). The program in the tracing section is self-contained: save it as flatten_trace.py and run it the same way.
Find the kth smallest element in a BST. Use an iterative inorder walk that stops early, give the time and space cost, handle invalid k, and say how a Morris traversal would change the space cost.
Sample Answer
The idea
An inorder traversal of a binary search tree (BST: left subtree keys smaller, right subtree keys larger) visits keys in increasing order (inorder means: walk the left subtree, then the node itself, then the right subtree). So the kth smallest key is simply the kth node an inorder walk visits, and you can stop the moment you reach it instead of walking the whole tree. The brute force is to collect all keys into a list and index it (O(n) time and O(n) space); stopping early avoids both.
The walk is iterative, with an explicit stack (a list used as a last-in first-out pile) in place of recursion. Go as far left as possible, pushing each node. Pop a node: that is the next smallest key, so count it. Then continue with that node's right subtree.
Code
Example tree:
50
/ \
30 70
/ \ / \
20 40 60 80
import random
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def kth_smallest(root, k, trace=None):
"""k is 1-based. Iterative inorder walk that stops at the kth node."""
if k < 1:
raise ValueError("k must be at least 1")
stack, cur = [], root
while stack or cur:
while cur:
stack.append(cur)
cur = cur.left
cur = stack.pop()
k -= 1
if trace is not None:
trace.append(f"pop {cur.key}, remaining k = {k}, stack = {[n.key for n in stack]}")
if k == 0:
return cur.key
cur = cur.right
raise ValueError("k is larger than the number of nodes")
def kth_smallest_morris(root, k):
"""O(1) extra space. Threads are removed as the walk goes, so the tree is restored."""
if k < 1:
raise ValueError("k must be at least 1")
answer, cur = None, root
while cur:
if cur.left is None:
k -= 1
if k == 0:
answer = cur.key
cur = cur.right
else:
pred = cur.left
while pred.right and pred.right is not cur:
pred = pred.right
if pred.right is None:
pred.right = cur # thread: remember how to come back
cur = cur.left
else:
pred.right = None # second arrival: remove thread
k -= 1
if k == 0:
answer = cur.key
cur = cur.right
if answer is None:
raise ValueError("k is larger than the number of nodes")
return answer
# 50
# / \
# 30 70
# / \ / \
# 20 40 60 80
tree = Node(50, Node(30, Node(20), Node(40)), Node(70, Node(60), Node(80)))
steps = []
print("3rd smallest:", kth_smallest(tree, 3, steps))
for s in steps:
print(" ", s)
for bad in (0, 8, -1):
for fn in (kth_smallest, kth_smallest_morris):
try:
fn(tree, bad)
except ValueError as e:
print(f"k={bad:>2} {fn.__name__}: ValueError: {e}")
def shape(node):
return None if node is None else (node.key, shape(node.left), shape(node.right))
def insert(root, key):
if root is None:
return Node(key)
if key < root.key:
root.left = insert(root.left, key)
else:
root.right = insert(root.right, key)
return root
rng = random.Random(23)
for _ in range(500):
keys = rng.sample(range(100), rng.randint(1, 25))
t = None
for key in keys:
t = insert(t, key)
before = shape(t)
ordered = sorted(keys)
for k in range(1, len(keys) + 1):
assert kth_smallest(t, k) == ordered[k - 1] == kth_smallest_morris(t, k)
assert shape(t) == before # Morris left the tree unchanged
print("500 random trees: both versions match sorted(); tree unchanged after Morris")
chain = None
for v in range(5000, 0, -1):
chain = Node(v, None, chain)
print("5000-node chain, k = 4999 ->", kth_smallest(chain, 4999), "| Morris ->", kth_smallest_morris(chain, 4999))
Run in a python:3.12 container, it prints:
3rd smallest: 40
pop 20, remaining k = 2, stack = [50, 30]
pop 30, remaining k = 1, stack = [50]
pop 40, remaining k = 0, stack = [50]
k= 0 kth_smallest: ValueError: k must be at least 1
k= 0 kth_smallest_morris: ValueError: k must be at least 1
k= 8 kth_smallest: ValueError: k is larger than the number of nodes
k= 8 kth_smallest_morris: ValueError: k is larger than the number of nodes
k=-1 kth_smallest: ValueError: k must be at least 1
k=-1 kth_smallest_morris: ValueError: k must be at least 1
500 random trees: both versions match sorted(); tree unchanged after Morris
5000-node chain, k = 4999 -> 4999 | Morris -> 4999
Worked trace
For k = 3 on the tree above: the walk pushes 50, 30, 20, then pops 20 (first smallest, remaining k 2, stack holds 50 and 30). Popping 20 leaves its right subtree empty, so the next pop is 30 (remaining 1; 30's right subtree begins with 40, which is pushed). The next pop is 40, remaining 0, so 40 is returned. The stack still holds 50, and the other half of the tree was never visited.
Invalid k
k < 1 raises ValueError before any work. A k larger than the number of nodes lets the loop run out of nodes, and the function then raises ValueError too (printed for k = 0, -1 and 8 on a 7-node tree). Raising is better than returning None or a sentinel (a special placeholder value, such as -1, that stands for "no result"), because a placeholder could be a real key.
Complexity
- Time O(h + k), where h is the height counted in edges (the 7-node example has h = 2). Every node that is pushed is either popped (at most k pops happen) or still sitting on the stack when the walk stops, and the stack never holds more than one root-to-node path, which is at most h + 1 nodes. So there are at most k + h + 1 pushes and exactly k pops. If k is small this is much less than n. Counting from the printed trace for k = 3: the pushes are 50, 30, 20 and then 40, which is 4 pushes and 3 pops, against a bound of 3 + 2 + 1 = 6, while the tree has 7 nodes.
- Space O(h) for the stack. For a balanced tree that is O(log n); for a chain it is O(n).
- The loop uses no recursion, so a 5,000-node chain is no problem (printed), where a recursive version would hit CPython's default limit of 1000 nested calls.
Morris traversal and O(1) space
Morris traversal walks the tree without a stack by temporarily rewiring it. For a node with a left subtree, find its inorder predecessor (the node visited just before it, which is the rightmost node of that left subtree). If the predecessor's right pointer is empty, set it to point back at the current node (a thread: a temporary extra pointer that lets the walk climb back without a stack) and descend left. When the walk arrives at the node again, it finds the thread, removes it, visits the node, and goes right. A node with no left child is visited immediately. Every thread that is set is cleared when the walk returns to its node, so every pointer is restored by the end.
kth_smallest_morris above shows it. On the 7-node tree the thread for 50 is the pointer from 40 (the rightmost node of 50's left subtree) back to 50, and the thread for 30 is the pointer from 20 back to 30. This instrumented walk prints every thread set, every visit and every thread removed, for the full traversal and for a walk stopped after the third visit:
class Node:
def __init__(self, key, left=None, right=None):
self.key = key
self.left = left
self.right = right
def morris_inorder_trace(root, stop_after=None):
"""Morris inorder walk that prints every thread event and every visit."""
visited, cur = [], root
while cur:
if cur.left is None:
visited.append(cur.key)
print(f"at {cur.key}: no left child, visit {cur.key}, go right")
if len(visited) == stop_after:
return visited
cur = cur.right
else:
pred = cur.left
while pred.right and pred.right is not cur:
pred = pred.right
if pred.right is None:
pred.right = cur
print(f"at {cur.key}: predecessor is {pred.key}, set thread {pred.key}.right -> {cur.key}, go left")
cur = cur.left
else:
pred.right = None
visited.append(cur.key)
print(f"at {cur.key}: thread found at {pred.key}, remove it, visit {cur.key}, go right")
if len(visited) == stop_after:
return visited
cur = cur.right
return visited
def build():
return Node(50, Node(30, Node(20), Node(40)), Node(70, Node(60), Node(80)))
print("full walk")
print("order:", morris_inorder_trace(build()))
print("stopping after the 3rd visit")
tree = build()
morris_inorder_trace(tree, stop_after=3)
leftover = tree.left.right.right
print("node 40 right pointer after stopping:", leftover.key if leftover else None)
Run in a python:3.12 container, it prints:
full walk
at 50: predecessor is 40, set thread 40.right -> 50, go left
at 30: predecessor is 20, set thread 20.right -> 30, go left
at 20: no left child, visit 20, go right
at 30: thread found at 20, remove it, visit 30, go right
at 40: no left child, visit 40, go right
at 50: thread found at 40, remove it, visit 50, go right
at 70: predecessor is 60, set thread 60.right -> 70, go left
at 60: no left child, visit 60, go right
at 70: thread found at 60, remove it, visit 70, go right
at 80: no left child, visit 80, go right
order: [20, 30, 40, 50, 60, 70, 80]
stopping after the 3rd visit
at 50: predecessor is 40, set thread 40.right -> 50, go left
at 30: predecessor is 20, set thread 20.right -> 30, go left
at 20: no left child, visit 20, go right
at 30: thread found at 20, remove it, visit 30, go right
at 40: no left child, visit 40, go right
node 40 right pointer after stopping: 50
Read the full walk like this. At 50 the thread 40 -> 50 is set and the walk goes left. At 30 the thread 20 -> 30 is set. Node 20 has no left child, so it is visited and the walk goes right, which follows the thread 20 -> 30 back up without any stack. Arriving at 30 again, the walk finds the thread, removes it and visits 30. The same pattern repeats for 50 (thread 40 -> 50) and for 70 (thread 60 -> 70). In the stopped walk the last line shows what early stopping costs: 40 still points to 50, a leftover thread that would corrupt the tree.
The space cost drops from O(h) to O(1), at three prices:
- Time: it runs the traversal to the end so every thread is removed, so it costs O(n) even when k is small. Stopping early would leave threads in the tree unless extra cleanup code walked back and removed them.
- The tree is modified while the walk runs. A concurrent reader (another thread looking at the tree at the same moment) would see the temporary pointers, so it is not safe on a shared tree without locking (a guard that lets one thread at a time use the tree).
- More code and a harder bug surface than the stack version.
The two versions were compared with sorted(keys) for every k on 500 random trees, and the tree's shape was compared before and after the Morris call to confirm it was restored (the printed 500 random trees line).
Edge cases and common mistakes
- k counted from 1 versus 0: be explicit.
- Decrementing and checking
k == 0after the pop, not before, or you return the wrong node. - Continuing to the right subtree before counting the node (that visits keys out of order).
- Duplicates: if the tree allows them, this returns the kth smallest by position, so duplicates occupy several positions.
- Empty tree: no node is ever popped, so any k raises.
Running the code
Save as kth_smallest_bst.py and run python kth_smallest_bst.py with Python 3.12. Standard library only.
Count the nodes, the leaves and the internal nodes of a binary tree, once recursively and once iteratively. State the base cases and the recursion depth on a very unbalanced tree.
Sample Answer
The idea in plain words
Three counts, one traversal. The total number of nodes is every node visited. A leaf is a node with no children at all. An internal node is a node with at least one child. Those definitions split every node into exactly one of the two groups, so internal = nodes - leaves.
Be careful with a node that has exactly one child: it is internal, not a leaf. In the example tree below, node 3 has only a right child (6), so it is internal; the leaves are 4, 5 and 6.
1
/ \
2 3
/ \ \
4 5 6
Height convention: height counts edges, so an empty tree has height -1 and a single node has height 0.
Base cases
- Empty tree (
None): 0 nodes, 0 leaves, 0 internal. This ends the recursion when it walks off the tree. - A node with no children: 1 node, 1 leaf, 0 internal. This is the second stopping point, and it is what distinguishes a leaf from an internal node with a missing child.
For any other node, the recursive answer combines the two subtrees: nodes = 1 + left nodes + right nodes, leaves = left leaves + right leaves (the node itself is not a leaf), and internal = 1 + left internal + right internal. A single node by itself is a leaf, so a tree of one node has 1 node, 1 leaf and 0 internal nodes.
Code
Both versions return the same three numbers. The iterative one uses an explicit stack (a list where the newest item comes off first) and does the counting when it pops a node, so it needs no recursion. Because it pushes the right child first and the left second, it meets the leaves from left to right, which also lists the leaf values.
import random
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def count_recursive(node, depth=1, deepest=None):
"""Returns (nodes, leaves, internal_nodes). deepest is an optional [max_depth] tracker."""
if node is None: # base case 1: empty tree
return 0, 0, 0
if deepest is not None:
deepest[0] = max(deepest[0], depth)
if node.left is None and node.right is None:
return 1, 1, 0 # base case 2: a leaf has no children at all
ln, ll, li = count_recursive(node.left, depth + 1, deepest)
rn, rl, ri = count_recursive(node.right, depth + 1, deepest)
return 1 + ln + rn, ll + rl, 1 + li + ri # the node itself has a child, so it is internal
def count_iterative(root, on_step=None):
"""Same counts with an explicit stack. Also lists the leaf values, left to right."""
nodes = leaves = internal = 0
leaf_values = []
stack = [root] if root else []
while stack:
node = stack.pop()
nodes += 1
if node.left is None and node.right is None:
leaves += 1
leaf_values.append(node.val)
else:
internal += 1
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
if on_step:
on_step(node, nodes, leaves, internal)
return nodes, leaves, internal, leaf_values
# The example tree. Node 3 has one child, so it is internal, not a leaf.
# 1
# / \
# 2 3
# / \ \
# 4 5 6
tree = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print("recursive (nodes, leaves, internal):", count_recursive(tree))
print("iterative (nodes, leaves, internal, leaf values):", count_iterative(tree))
print()
print("iterative trace:")
count_iterative(tree, on_step=lambda node, n, l, i: print(
f" pop {node.val}: nodes={n} leaves={l} internal={i}"))
print()
print("empty tree:", count_recursive(None), " single node:", count_recursive(Node(9)))
# Recursion depth: a chain versus a balanced tree.
def left_chain(length):
root = None
for v in range(length):
root = Node(v, left=root)
return root
def perfect(height):
return None if height < 0 else Node(0, perfect(height - 1), perfect(height - 1))
for label, t in (("chain of 500 nodes", left_chain(500)),
("perfect tree, height 8 (511 nodes)", perfect(8))):
deepest = [0]
count_recursive(t, deepest=deepest)
print(f"{label}: deepest recursive call = {deepest[0]}")
big = left_chain(100000)
print("iterative on a 100000-node chain:", count_iterative(big)[:3])
try:
count_recursive(big)
except RecursionError:
print("recursive on the same chain: RecursionError")
# Check both against a level-order count on random trees; full trees have leaves = internal + 1.
def random_tree(rng, size):
if size == 0:
return None
left_size = rng.randint(0, size - 1)
return Node(rng.randrange(1000), random_tree(rng, left_size),
random_tree(rng, size - 1 - left_size))
def random_full_tree(rng, depth):
if depth == 0 or rng.random() < 0.3:
return Node(0)
return Node(0, random_full_tree(rng, depth - 1), random_full_tree(rng, depth - 1))
rng = random.Random(0)
for _ in range(500):
t = random_tree(rng, rng.randint(0, 15))
queue, seen = deque([t] if t else []), []
while queue:
node = queue.popleft()
seen.append(node)
queue.extend(c for c in (node.left, node.right) if c)
leaves = sum(1 for n in seen if not n.left and not n.right)
expected = (len(seen), leaves, len(seen) - leaves)
assert count_recursive(t) == expected == count_iterative(t)[:3]
full = random_full_tree(rng, 5)
n, l, i = count_recursive(full)
assert l == i + 1
print("500 random trees: recursive == iterative == level-order count; full trees: leaves = internal + 1")
Run in a python:3.12 container, it prints:
recursive (nodes, leaves, internal): (6, 3, 3)
iterative (nodes, leaves, internal, leaf values): (6, 3, 3, [4, 5, 6])
iterative trace:
pop 1: nodes=1 leaves=0 internal=1
pop 2: nodes=2 leaves=0 internal=2
pop 4: nodes=3 leaves=1 internal=2
pop 5: nodes=4 leaves=2 internal=2
pop 3: nodes=5 leaves=2 internal=3
pop 6: nodes=6 leaves=3 internal=3
empty tree: (0, 0, 0) single node: (1, 1, 0)
chain of 500 nodes: deepest recursive call = 500
perfect tree, height 8 (511 nodes): deepest recursive call = 9
iterative on a 100000-node chain: (100000, 1, 99999)
recursive on the same chain: RecursionError
500 random trees: recursive == iterative == level-order count; full trees: leaves = internal + 1
Reading the trace
Each line shows the counters after one pop. Node 1 is internal (nodes 1, internal 1), then 2 is internal. Node 4 is the first leaf (leaves 1), then 5 (leaves 2). Node 3 comes next and is internal despite having just one child. Node 6 is the last leaf. The final counts are 6 nodes, 3 leaves and 3 internal nodes, and the leaf values in left-to-right order are [4, 5, 6].
Recursion depth on a very unbalanced tree
The recursion goes as deep as the longest path from the root to a leaf. For a non-empty tree that is height + 1 calls, because the leaf stops without calling into None. The run shows 500 calls for a chain of 500 nodes and 9 for a perfect tree of height 8. So the call stack grows like n for a chain and like log2(n) for a balanced tree.
CPython's default limit is 1000 frames (nested calls). A one-sided chain of more than about a thousand nodes therefore raises RecursionError: the run shows it on a 100000-node chain, where the iterative version finishes and reports 100000 nodes, 1 leaf and 99999 internal nodes. When trees may be deep, ship the iterative version, or accept the recursive one only with a known bound on depth.
Complexity
- Time O(n): every node is visited exactly once and does constant work.
- Recursive version: extra space O(h) for the call stack, where h is the height. That is O(n) on a chain and O(log n) on a balanced tree.
- Iterative version: the stack holds at most h + 1 nodes, so also O(h) in the worst case; on a left chain it never holds more than one node, since each pop pushes a single child. The leaf-value list adds O(number of leaves).
Edge cases and common mistakes
- Empty tree gives
(0, 0, 0). A single node gives(1, 1, 0): it is a leaf, and it is not counted as internal. - Counting a node with one child as a leaf is the most common error. A leaf test must require both children to be missing.
- Using leaves = internal + 1 for every tree is wrong. That identity holds only for full binary trees, where every node has zero or two children. The example tree has leaves 3 and internal 3, so it fails there. The check in the code asserts the identity only on randomly generated full trees.
- Skipping the second base case (the one for a node with no children) loses every leaf. Take leaf 4 in the example tree: both of its children are
None, and each empty child reports 0 leaves, so 4 would add 0 + 0 and report 0 leaves. Every node above it only adds up its children's leaf counts, so the whole tree would report 0 leaves. The fix is the explicit rule: when a node has no left child and no right child, it returns 1 leaf (the base case in the code), rather than trying to derive it from its empty children.
Running the code
Save the listing as count_nodes.py and run it with Python 3.12. It uses only the standard library, so there is nothing to install.
python3 count_nodes.py
Unlock Full Question Bank
Get access to all Trees and Binary Search Trees interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.