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.
A BST is too large for memory and lives on disk. How would you find the kth smallest element, or iterate in order, with as few disk reads as possible and only a few megabytes of memory? Say what metadata you would store.
Sample Answer
The idea
On disk, the cost that matters is the number of page reads. A page (or block) is the smallest unit the disk hands over, commonly 4 KiB, and reading a page is far slower than touching memory, so you count page reads, not comparisons. A classic BST (binary search tree: smaller keys left, larger keys right) with one node per page makes every step of a search a page read, so a balanced tree of a billion keys needs about 30 reads for one lookup.
Two ideas fix both parts of the question:
- Store a count in the structure so the k-th smallest is found by descending, not by walking. Each node keeps the size of its left subtree (or, in a wider tree, each child pointer keeps the number of keys beneath it). At a node: if k is less than the left count, go left; if equal, this is the answer; otherwise subtract the left count plus one and go right. One root-to-leaf path, no scan.
- Make the tree wide. Pack many keys into one page so each step eliminates hundreds of candidates, not half. That is a B-tree (a search tree whose nodes hold many sorted keys and many children). The number of children an inner page can hold is its fanout; an inner page is a page that routes the search (it holds keys and child pointers, not the data entries), while a leaf page holds the stored keys themselves. The B+ tree variant keeps all keys in leaf pages that are linked in order, which is exactly what in-order iteration wants.
Heights and depths count edges (empty tree -1, single node 0). A tree with 3 levels has height 2.
Here is a tiny B+ tree over 12 keys, with leaf capacity 3 and fanout 2. Each entry on an inner page is (smallest key below, number of keys below), so the root's entries say "the left child starts at key 3 and holds 6 keys, the right child starts at key 41 and holds 6 keys":
root: [(3, 6), (41, 6)]
/ \
inner: [(3, 3), (22, 3)] inner: [(41, 3), (70, 3)]
/ \ / \
[3 8 15] [22 31 40] [41 50 61] [70 77 90]
The first lines of the output print exactly these pages (page 6 is the root, pages 4 and 5 the inner pages, pages 0 to 3 the leaves).
Metadata to store
- Binary BST on disk: per node
(key, left_pid, right_pid, left_count), whereleft_countis the number of keys in the left subtree. No need to read a child to learn its size. - B+ tree inner page: a list of
(min_key, child_pid, key_count). The minimum key routes searches, the count routes rank queries. - B+ tree leaf page: the sorted keys and the page id of the next leaf, so a scan never goes back up the tree.
- Maintenance: an insert or delete must adjust the count on every page along the root-to-leaf path. Those pages are the ones a split or merge already touches, but a simple insert that fits in a leaf now rewrites the whole path (about height + 1 pages) instead of one leaf. That write cost is the price of fast rank queries; if the data is read-mostly or bulk loaded, it is free.
Approach
- k-th smallest (0-based rank k): at each inner page walk the entries, subtracting each child's count from k until k falls inside a child, then descend into it. In the leaf the answer is
keys[k]. Reads: one per level. - In-order iteration from rank k: descend the same way to the leaf containing rank k, yield the keys from there on, then follow the
next_leafpointer. State held: the current leaf, one page. Reads: one per leaf of 64 keys here, in the order the leaves are stored. - Memory of a few megabytes: a page cache that holds the pages near the root. The root and the first inner levels are touched by every query, so they stay cached, and a rank query then costs only the reads below the cached levels.
- If it must stay a binary tree: put a connected subtree of height about log2(fanout) into each page instead of one node. With 64 binary nodes per page that is 6 levels (2^6 - 1 = 63 nodes), so one read now covers 6 steps down. A tree of 10^9 keys has about 30 levels, so it needs 30 / 6 = 5 page reads instead of 30, close to the 4 of the B+ tree computed below. (This is arithmetic from the layout; the program runs the one-node-per-page version and the B+ tree.)
Code
Terms used in the code and below: a tree is bulk loaded when it is built once, in one pass, from already-sorted data (the leaves are written in order and packed full); read-mostly means queries far outnumber updates; a split divides an overfull page in two, a merge joins two underfull pages, and redistribution moves entries between neighbouring pages; to pin a page is to tell the cache never to evict it, and evicting is dropping the least recently used page to make room.
The program builds the same 100,000 sorted keys as a one-node-per-page binary tree and as a B+ tree, counts only reads that miss an LRU (least-recently-used) page cache, and checks every answer against the sorted list.
import random
from collections import OrderedDict
class Disk:
"""Pages live here; every read that gets past the cache is counted."""
def __init__(self):
self.pages, self.reads, self.sequential, self._last = {}, 0, 0, None
def write(self, page):
self.pages[len(self.pages)] = page
return len(self.pages) - 1
def read(self, pid):
self.reads += 1
if self._last is not None and pid == self._last + 1:
self.sequential += 1
self._last = pid
return self.pages[pid]
class PageCache:
"""LRU cache holding at most `capacity` pages: this is the 'few megabytes'."""
def __init__(self, disk, capacity):
self.disk, self.capacity, self.hot = disk, capacity, OrderedDict()
def get(self, pid):
if pid in self.hot:
self.hot.move_to_end(pid)
return self.hot[pid]
page = self.disk.read(pid)
self.hot[pid] = page
if len(self.hot) > self.capacity:
self.hot.popitem(last=False)
return page
# ---- binary BST, one node per page: page = (key, left_pid, right_pid, left_count) ----
def build_binary(disk, keys, lo, hi):
if lo >= hi:
return None
mid = (lo + hi) // 2
left = build_binary(disk, keys, lo, mid)
right = build_binary(disk, keys, mid + 1, hi)
return disk.write((keys[mid], left, right, mid - lo))
def kth_binary(cache, root, k):
pid = root
while True:
key, left, right, left_count = cache.get(pid)
if k < left_count:
pid = left
elif k == left_count:
return key
else:
k -= left_count + 1
pid = right
def kth_binary_no_counts(cache, root, k):
"""In-order walk until the k-th key: reads about k pages."""
stack, pid, seen = [], root, 0
while stack or pid is not None:
while pid is not None:
stack.append(cache.get(pid))
pid = stack[-1][1]
key, _, right, _ = stack.pop()
if seen == k:
return key
seen += 1
pid = right
def iter_binary_from_rank(cache, root, k):
stack, pid = [], root
while True:
key, left, right, left_count = cache.get(pid)
if k < left_count:
stack.append((key, right))
pid = left
elif k == left_count:
stack.append((key, right))
break
else:
k -= left_count + 1
pid = right
while stack:
key, right = stack.pop()
yield key
pid = right
while pid is not None:
key2, left2, right2, _ = cache.get(pid)
stack.append((key2, right2))
pid = left2
# ---- B+ tree: leaf = ("leaf", keys, next_leaf); node = ("node", [(min_key, child_pid, key_count), ...]) ----
def build_bplus(disk, keys, leaf_cap, fanout):
level = []
chunks = [keys[i:i + leaf_cap] for i in range(0, len(keys), leaf_cap)]
first = len(disk.pages)
for i, chunk in enumerate(chunks):
nxt = first + i + 1 if i + 1 < len(chunks) else None
level.append((chunk[0], disk.write(("leaf", chunk, nxt)), len(chunk)))
while len(level) > 1:
parents = []
for i in range(0, len(level), fanout):
group = level[i:i + fanout]
parents.append((group[0][0], disk.write(("node", group)), sum(c for _, _, c in group)))
level = parents
return level[0][1]
def descend_to_rank(cache, root, k, trace=None):
page = cache.get(root)
while page[0] == "node":
if trace is not None:
trace.append(f"inner page, children (min_key, count) = {[(m, c) for m, _, c in page[1]]}, rank left {k}")
for _, pid, count in page[1]:
if k < count:
page = cache.get(pid)
break
k -= count
if trace is not None:
trace.append(f"leaf page {page[1]}, rank within leaf {k} -> key {page[1][k]}")
return page, k
def kth_bplus(cache, root, k):
leaf, k = descend_to_rank(cache, root, k)
return leaf[1][k]
def iter_bplus_from_rank(cache, root, k):
leaf, k = descend_to_rank(cache, root, k)
while True:
yield from leaf[1][k:]
if leaf[2] is None:
return
leaf, k = cache.get(leaf[2]), 0
# ---- a tiny tree, to see one descent ----
tiny_keys = [3, 8, 15, 22, 31, 40, 41, 50, 61, 70, 77, 90]
tiny_disk = Disk()
tiny_root = build_bplus(tiny_disk, tiny_keys, 3, 2)
for pid, page in tiny_disk.pages.items():
if page[0] == "leaf":
print(f"page {pid}: leaf, keys {page[1]}, next leaf {page[2]}")
else:
print(f"page {pid}: inner, entries (min_key, child page, key count) = {page[1]}")
steps = []
descend_to_rank(PageCache(tiny_disk, 4), tiny_root, 7, steps) # rank 7 counting from 0
print("\n".join(steps))
print("sorted keys:", tiny_keys, "-> index 7 is", tiny_keys[7], "| disk reads:", tiny_disk.reads, "\n")
# ---- build both on the same 100,000 sorted keys ----
N, LEAF_CAP, FANOUT, CACHE = 100_000, 64, 64, 32
keys = sorted(random.Random(8).sample(range(10_000_000), N))
bd, td = Disk(), Disk()
broot = build_binary(bd, keys, 0, N)
troot = build_bplus(td, keys, LEAF_CAP, FANOUT)
print(f"binary BST: {len(bd.pages):,} pages | B+ tree: {len(td.pages):,} pages "
f"({-(-N // LEAF_CAP):,} leaves, {len(td.pages) - -(-N // LEAF_CAP)} inner pages)")
# ---- correctness against the sorted list ----
rng = random.Random(1)
ranks = set()
for _ in range(500):
k = rng.randrange(N)
assert kth_binary(PageCache(bd, 8), broot, k) == keys[k] == kth_bplus(PageCache(td, 8), troot, k)
start, m = rng.randrange(N), rng.randint(1, 300)
for it in (iter_binary_from_rank(PageCache(bd, 8), broot, start),
iter_bplus_from_rank(PageCache(td, 8), troot, start)):
got = [x for _, x in zip(range(m), it)]
assert got == keys[start:start + m]
ranks.add(k)
print("ranks checked:", len(ranks), "distinct")
# duplicate keys: the counts count entries, so a rank is a position in the sorted list, repeats included
dup = sorted(random.Random(5).choices(range(50), k=5000))
dd, dt = Disk(), Disk()
dup_binary, dup_bplus = build_binary(dd, dup, 0, len(dup)), build_bplus(dt, dup, LEAF_CAP, FANOUT)
assert all(kth_binary(PageCache(dd, 8), dup_binary, k) == dup[k] == kth_bplus(PageCache(dt, 8), dup_bplus, k)
for k in range(len(dup)))
print(f"duplicate keys: all {len(dup):,} ranks agree with the sorted list ({len(set(dup))} distinct values)")
# ---- disk reads per k-th query: 1,000 random ranks ----
qr = random.Random(2)
queries = [qr.randrange(N) for _ in range(1000)]
for label, disk, root, fn in (("binary BST + left counts", bd, broot, kth_binary),
("B+ tree + child counts", td, troot, kth_bplus)):
for cap in (1, CACHE):
disk.reads = 0
cache = PageCache(disk, cap)
for k in queries:
fn(cache, root, k)
print(f"{label:<26} cache {cap:>2} pages: {disk.reads / len(queries):5.2f} disk reads per query")
bd.reads = 0
print("binary BST, no counts, k = 50,000:", end=" ")
kth_binary_no_counts(PageCache(bd, CACHE), broot, 50_000)
print(f"{bd.reads:,} disk reads")
bd.reads = 0
kth_binary(PageCache(bd, CACHE), broot, 50_000)
print(f"binary BST, with counts, k = 50,000: {bd.reads} disk read")
# ---- iteration: 1,000 consecutive keys starting at rank 50,000 ----
for label, disk, root, fn in (("binary BST", bd, broot, iter_binary_from_rank),
("B+ tree", td, troot, iter_bplus_from_rank)):
disk.reads = disk.sequential = 0
it = fn(PageCache(disk, CACHE), root, 50_000)
for _ in range(1000):
next(it)
print(f"iterate 1,000 keys, {label:<10}: {disk.reads:>4} disk reads, {disk.sequential:>3} of them adjacent to the previous page")
# the same 1,000 ranks asked one by one with kth_bplus instead of walking the leaf chain
for cap in (1, CACHE):
td.reads = 0
cache = PageCache(td, cap)
for k in range(50_000, 51_000):
kth_bplus(cache, troot, k)
print(f"1,000 consecutive kth_bplus calls, cache {cap:>2} pages: {td.reads:>5} disk reads")
# ---- the same arithmetic at one billion keys (computed from the page layout, not run) ----
def levels(n, page_bytes=4096, key=8, ptr=8, count=8):
leaf_cap = page_bytes // key
fanout = page_bytes // (key + ptr + count)
width, out = -(-n // leaf_cap), []
out.append(("leaf", width))
while width > 1:
width = -(-width // fanout)
out.append(("inner", width))
return leaf_cap, fanout, out
n = 1_000_000_000
leaf_cap, fanout, out = levels(n)
print(f"\n{n:,} keys, 4096-byte pages: leaf holds {leaf_cap}, inner page holds {fanout} entries")
print("pages per level, leaves first:", [(name, f"{w:,}") for name, w in out])
cache_pages = 4 * 1024 * 1024 // 4096
cached_levels = 0
total = 0
for name, w in reversed(out):
if total + w <= cache_pages:
total += w
cached_levels += 1
print(f"a 4 MiB cache = {cache_pages} pages; it holds the top {cached_levels} levels ({total} pages)")
binary_depth = n.bit_length() - 1
binary_cached = (cache_pages + 1).bit_length() - 1
print(f"B+ tree: {len(out)} levels, so {len(out)} reads uncached and {len(out) - cached_levels} with that cache")
print(f"binary BST: height {binary_depth} edges, {binary_depth + 1} reads uncached; the cache holds the top "
f"{binary_cached} levels, leaving {binary_depth + 1 - binary_cached}")
Output
page 0: leaf, keys [3, 8, 15], next leaf 1
page 1: leaf, keys [22, 31, 40], next leaf 2
page 2: leaf, keys [41, 50, 61], next leaf 3
page 3: leaf, keys [70, 77, 90], next leaf None
page 4: inner, entries (min_key, child page, key count) = [(3, 0, 3), (22, 1, 3)]
page 5: inner, entries (min_key, child page, key count) = [(41, 2, 3), (70, 3, 3)]
page 6: inner, entries (min_key, child page, key count) = [(3, 4, 6), (41, 5, 6)]
inner page, children (min_key, count) = [(3, 6), (41, 6)], rank left 7
inner page, children (min_key, count) = [(41, 3), (70, 3)], rank left 1
leaf page [41, 50, 61], rank within leaf 1 -> key 50
sorted keys: [3, 8, 15, 22, 31, 40, 41, 50, 61, 70, 77, 90] -> index 7 is 50 | disk reads: 3
binary BST: 100,000 pages | B+ tree: 1,589 pages (1,563 leaves, 26 inner pages)
ranks checked: 497 distinct
duplicate keys: all 5,000 ranks agree with the sorted list (50 distinct values)
binary BST + left counts cache 1 pages: 15.67 disk reads per query
binary BST + left counts cache 32 pages: 13.03 disk reads per query
B+ tree + child counts cache 1 pages: 3.00 disk reads per query
B+ tree + child counts cache 32 pages: 1.46 disk reads per query
binary BST, no counts, k = 50,000: 50,001 disk reads
binary BST, with counts, k = 50,000: 1 disk read
iterate 1,000 keys, binary BST: 1010 disk reads, 19 of them adjacent to the previous page
iterate 1,000 keys, B+ tree : 18 disk reads, 15 of them adjacent to the previous page
1,000 consecutive kth_bplus calls, cache 1 pages: 3000 disk reads
1,000 consecutive kth_bplus calls, cache 32 pages: 18 disk reads
1,000,000,000 keys, 4096-byte pages: leaf holds 512, inner page holds 170 entries
pages per level, leaves first: [('leaf', '1,953,125'), ('inner', '11,489'), ('inner', '68'), ('inner', '1')]
a 4 MiB cache = 1024 pages; it holds the top 2 levels (69 pages)
B+ tree: 4 levels, so 4 reads uncached and 2 with that cache
binary BST: height 29 edges, 30 reads uncached; the cache holds the top 10 levels, leaving 20
Reading the output
- The tiny-tree trace: rank 7 at the root (counts 6 and 6) skips the first child (7 is not below 6), leaving rank 1 in the second child; that inner page's first child has 3 keys and 1 is below 3, so it descends there; the leaf
[41, 50, 61]holds the answer at position 1: key 50, three page reads for three levels. - 100,000 keys need 100,000 pages as a one-node-per-page binary tree and 1,589 pages as a B+ tree (1,563 leaves plus 26 inner pages).
- Rank queries over 1,000 random ranks: the binary tree with counts needs 15.67 disk reads per query with a one-page cache (effectively none) and 13.03 with a 32-page cache. The B+ tree needs 3.00 and 1.46. With 32 pages all 26 inner pages (25 above the leaves plus the root) fit in the cache, but the leaf reads compete for the same slots, so some inner pages are still evicted and re-read: 1.46 reads per query, a little more than the one unavoidable leaf read.
- Without counts the binary tree must walk in order: 50,001 disk reads to reach rank 50,000. That rank happens to be the root of this balanced tree, so with counts it is answered by 1 read; the random ranks above are the fair comparison.
- Iterating 1,000 consecutive keys takes 1,010 disk reads on the binary tree and 18 on the B+ tree, and 15 of those 18 are for the page right after the previous one (bulk loading wrote leaves next to each other). After many random inserts and splits the leaves are scattered, so fewer reads are adjacent.
- At one billion keys with 4 KiB pages (8-byte keys, 8-byte page ids, 8-byte counts; page headers ignored), a leaf holds 4096 / 8 = 512 keys and an inner page 4096 / 24 = 170 entries (170.7 rounded down; each entry is a key, a page id and a count, 24 bytes): 1,000,000,000 / 512 = 1,953,125 leaves, then 1,953,125 / 170 = 11,489 inner pages, then 11,489 / 170 = 68, then 1 root (each division rounded up), so 4 levels. A 4 MiB cache is 1,024 pages and holds the top two levels (69 pages), so a rank query costs 2 disk reads. The binary tree has height 29 edges (30 reads uncached); the same cache holds only its top 10 levels, so it still needs 20 reads. These last figures come from the page-layout arithmetic printed by the program, not from running a billion keys.
Complexity
- k-th smallest: O(h) page reads with counts, where h is the height in edges: about log2 n for the binary tree and about log_f n for fanout f. Without counts: O(k) reads.
- CPU per page: O(f) to scan the entries of an inner page (or O(log f) with binary search inside the page).
- In-order iteration of m keys: about m / leaf_capacity + h page reads, with one leaf and O(h) pages of state.
- Update: O(h) page reads and writes along one path, to maintain counts.
- Memory: the cache is bounded by its page count; the program uses no recursion in queries or iteration (the builder recurses to depth log2 n only for the binary layout).
Edge cases and common mistakes
- Rank out of range (k below 0 or at least n): check against the root's total count before descending; the code above assumes a valid rank.
- Duplicate keys: the counts count entries, not distinct keys, so the rank is a position in sorted order with duplicates included.
- Using key comparisons to answer a rank query, or storing only a total at the root, which does not tell you which child holds rank k.
- Letting the counts drift: every insert, delete, split, merge and redistribution must update the counts on the pages it changes, in the same write that changes the keys.
- Treating one cached leaf as enough for random access: caching helps the top of the tree, while leaf reads for random ranks stay cold.
- Iterating by repeated k-th lookups (rank 0, 1, 2, ...) instead of following the leaf chain. Each key repeats a root-to-leaf descent: 1,000 consecutive ranks cost 3,000 disk reads with a one-page cache (3 levels per key) against 18 for the leaf chain. A 32-page cache hides most of those reads (18 as well, in the output), but the descent is still repeated for every key, and the saving then depends on the cache.
Running the code
python3.12 disk_bst_kth.py
Save the code block as disk_bst_kth.py. Standard library only (random, collections).
Check whether a binary tree is height-balanced without using recursion. Emulate a postorder walk with an explicit stack, work out how you know each node's children have been finished, and explain how you carry heights and detect the first imbalance. State the time and space cost.
Sample Answer
The idea in plain words
A binary tree is height-balanced when, at every node, the heights of the left and right subtrees differ by at most 1. The height of a node is the number of edges on the longest downward path to a leaf. Heights and depths here count edges (empty tree -1, single node 0).
To know a node's balance you need both children's heights first, so the work happens in postorder: left subtree, right subtree, then the node. Recursion does this for free because the call stack remembers where it was. Without recursion you keep that memory yourself in an explicit stack (a list used as last-in-first-out) and you must answer one question each time you look at the node on top: "have both of its children been finished yet?"
Brute force and why it is not enough
The obvious recursive check calls height(node) at every node. Each height call walks the whole subtree, so a chain (every node has one child) costs n + (n-1) + ... = O(n^2). The fix, recursive or not, is to compute each height once and compare as you return. A recursive version of that is still limited by CPython's default recursion limit of 1000 frames, and the output below shows it raising RecursionError on a 5000-node chain. That is the practical reason to write the iterative form.
Approach
- Walk down the left spine (from a node, keep taking its left child: the chain of left children down to the first node with no left child), pushing every node on the stack, until you fall off the tree.
- Look at the node on top of the stack (
top). Iftophas a right child that has not been finished, go into that right subtree and repeat step 1. - Otherwise both children are finished or absent, so pop
top. Read the left and right heights (an absent child counts as -1), setheight[top] = 1 + max(left, right), and compareabs(left - right). - If the difference is more than 1, return
Falseimmediately. This is the first imbalance in postorder: a node whose children are both finished and which has no unbalanced node anywhere below it (everything below it came earlier in postorder and passed). Nothing after it is visited. It is not necessarily the deepest violation in the tree: a violation deeper down in a later, right-hand subtree is never reached. - Remember the node you just popped in
last.
How you know a node's children are finished. last is the most recently finished node. When you come back to top, there are three cases. If top has no right child, the left subtree is the only one and it has just finished. If last is top.right, the right subtree has just finished (and the left finished before it). If top has a right child and last is not that child, you have come up from the left subtree, so the right subtree has not started. A visited flag on each stack entry works too; last avoids storing a flag per entry.
How heights are carried. height is a dictionary keyed by the node object itself (each node is its own unique key, so no two nodes share an entry even when their values are equal). When a node is finished, its children's entries are removed with pop, so the dictionary holds only finished nodes whose parent is still unfinished. That is at most one entry per node on the stack, which is O(h) for a tree of height h, instead of n.
Code
import random
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def is_balanced(root, log=None, stats=None):
"""True if every node's subtree heights differ by at most 1. Heights count edges."""
height = {} # node -> height, kept only until the parent is finished
stack, cur, last = [], root, None
while stack or cur:
if cur: # walk down the left spine
stack.append(cur)
cur = cur.left
continue
top = stack[-1]
if log is not None:
move = "go into right subtree" if top.right and last is not top.right else "pop"
log.append(f"at {top.val}: last={last.val if last else None}, right child="
f"{top.right.val if top.right else None} -> {move}")
if top.right and last is not top.right:
cur = top.right # right subtree not done yet: go into it first
continue
stack.pop() # both children are finished (or absent): finish this node
hl = height.pop(top.left) if top.left else -1
hr = height.pop(top.right) if top.right else -1
height[top] = 1 + max(hl, hr)
if log is not None:
log.append(f"finish {top.val}: left height {hl}, right height {hr}, "
f"height {height[top]}, stack {[n.val for n in stack]}")
if stats is not None:
stats["peak_stack"] = max(stats["peak_stack"], len(stack) + 1)
stats["peak_heights"] = max(stats["peak_heights"], len(height))
if abs(hl - hr) > 1:
if log is not None:
log.append(f"node {top.val} is unbalanced: {hl} vs {hr}, stop")
return False
last = top
return True
def is_balanced_recursive(node): # reference; depth is limited by the recursion limit
def h(n):
if not n:
return -1
a, b = h(n.left), h(n.right)
if a is None or b is None or abs(a - b) > 1:
return None
return 1 + max(a, b)
return h(node) is not None
def random_tree(rng, depth):
if depth == 0 or rng.random() < 0.2:
return None
return Node(rng.randint(1, 9), random_tree(rng, depth - 1), random_tree(rng, depth - 1))
def complete(depth): # perfect tree with 2^(depth+1)-1 nodes
return None if depth < 0 else Node(1, complete(depth - 1), complete(depth - 1))
if __name__ == "__main__":
# 1
# / \
# 2 3
# / \ /
# 4 5 7
# /
# 6
ok = Node(1, Node(2, Node(4, Node(6)), Node(5)), Node(3, Node(7)))
log = []
print("balanced:", is_balanced(ok, log))
print("\n".join(log))
# 1
# /
# 2
# /
# 3
bad = Node(1, Node(2, Node(3)))
log = []
print("balanced:", is_balanced(bad, log))
print("\n".join(log))
print("empty tree:", is_balanced(None), "| single node:", is_balanced(Node(1)))
rng = random.Random(11)
yes = no = 0
for _ in range(500):
t = random_tree(rng, 6)
got = is_balanced(t)
assert got == is_balanced_recursive(t)
yes, no = yes + got, no + (not got)
print("random trees checked: 500 | balanced:", yes, "| unbalanced:", no)
chain = None
for v in range(5000):
chain = Node(v, chain, None)
stats = {"peak_stack": 0, "peak_heights": 0}
print("5000-node left chain balanced:", is_balanced(chain, stats=stats), stats)
stats = {"peak_stack": 0, "peak_heights": 0}
print("perfect tree of 2047 nodes balanced:", is_balanced(complete(10), stats=stats), stats)
try:
is_balanced_recursive(chain)
except RecursionError:
print("recursive version on the chain: RecursionError")
Output:
balanced: True
at 6: last=None, right child=None -> pop
finish 6: left height -1, right height -1, height 0, stack [1, 2, 4]
at 4: last=6, right child=None -> pop
finish 4: left height 0, right height -1, height 1, stack [1, 2]
at 2: last=4, right child=5 -> go into right subtree
at 5: last=4, right child=None -> pop
finish 5: left height -1, right height -1, height 0, stack [1, 2]
at 2: last=5, right child=5 -> pop
finish 2: left height 1, right height 0, height 2, stack [1]
at 1: last=2, right child=3 -> go into right subtree
at 7: last=2, right child=None -> pop
finish 7: left height -1, right height -1, height 0, stack [1, 3]
at 3: last=7, right child=None -> pop
finish 3: left height 0, right height -1, height 1, stack [1]
at 1: last=3, right child=3 -> pop
finish 1: left height 2, right height 1, height 3, stack []
balanced: False
at 3: last=None, right child=None -> pop
finish 3: left height -1, right height -1, height 0, stack [1, 2]
at 2: last=3, right child=None -> pop
finish 2: left height 0, right height -1, height 1, stack [1]
at 1: last=2, right child=None -> pop
finish 1: left height 1, right height -1, height 2, stack []
node 1 is unbalanced: 1 vs -1, stop
empty tree: True | single node: True
random trees checked: 500 | balanced: 113 | unbalanced: 387
5000-node left chain balanced: False {'peak_stack': 5000, 'peak_heights': 1}
perfect tree of 2047 nodes balanced: True {'peak_stack': 11, 'peak_heights': 11}
recursive version on the chain: RecursionError
Worked trace
The first tree in the driver:
1
/ \
2 3
/ \ /
4 5 7
/
6
The code prints two kinds of line. An at line is the decision made each time a node is on top of the stack: it shows last (the node finished most recently), the top node's right child, and the move chosen (go into right subtree when the top has a right child that is not last, otherwise pop). A finish line follows each pop; its stack column is the stack after the pop. Read the first finish line: node 6 is a leaf, so both heights are -1 and its height is 1 + max(-1, -1) = 0; after 6 is popped the stack still holds 1, 2 and 4. Node 4 has only a left child: heights 0 and -1 differ by 1, which is allowed, so its height is 1. Node 5 is a leaf. Node 2 has left height 1 and right height 0, so its height is 2. Node 7 and then node 3 follow (3 has left height 0 and right -1, so its height is 1). The root has left height 2 and right height 1, so the tree is balanced and the function returns True.
To see the three-way decision on real values, follow node 2. The walk down the left spine pushes 1, 2, 4, 6. After 6 and 4 are finished, node 2 is on top with last=4: it has a right child 5 and last is not 5, so the code arrived from the left subtree and the right one has not started (go into right subtree). The walk pushes 5, finishes it, and node 2 is on top again, now with last=5, which is its right child, so both subtrees are done (pop). Node 4, which has no right child, never needs the check: its at line says pop as soon as 6 is finished. The root repeats the pattern at the end: last=2 and right child 3 means go right, last=3 means pop.
The second tree is the chain 1, 2, 3 going left. After finishing 3 and 2, node 1 has left height 1 and right height -1. The difference is 2, so the code logs the stop and returns False.
Complexity
- Time: O(n) for n nodes. Each node is pushed once, popped once, and gets one O(1) dictionary update. An early
Falsestops sooner but never costs more. - Space: O(h) auxiliary, where h is the tree height. The stack holds at most h + 1 nodes and the height dictionary at most one entry per stack level. The driver prints the peaks: on the perfect tree of 2047 nodes (height 10) both are 11. On the 5000-node left chain the stack peaks at 5000 because the walk down pushes the whole chain before anything finishes, so on a skewed tree h is close to n and O(h) is O(n).
- The input tree itself is not counted, and nothing is recursive, so the 5000-node chain is handled while the recursive reference raises
RecursionError.
Edge cases and common mistakes
- Empty tree and single node are balanced; the code returns
Truefor both. - A node with only a left child needs
top.rightto be tested before comparing withlast;top.right and last is not top.rightdoes that. In the trace, node 4 has no right child andlastis 6. Testing onlylast is not top.rightwould be true there (6 is notNone), socurwould be set to the empty right child and node 4 would stay on top, never popped; testingtop.rightfirst is what avoids this. - Checking only the root's two subtree heights. Balance is required at every node: a root can look even while a deep subtree is lopsided.
- Treating "first imbalance" as the top-most one. The first failure found in postorder has no unbalanced node below it; the root can be perfectly balanced locally while a node deeper down is not.
Follow-ups and how the answer changes
- O(1) extra space: Morris traversal (an advanced technique that temporarily threads child pointers back to ancestors so no stack is needed) is the usual route for inorder and preorder; postorder with Morris is much more awkward, so interviewers rarely expect it for this problem.
- Also return the height of the whole tree, or the most unbalanced node: drop the early
return Falseand record the node where the difference is largest while the loop runs to the end. - Balance defined by node count instead of height changes what is stored and compared: keep subtree sizes instead of heights and apply the size rule you are given at each node.
Running the code
# Python 3.12, standard library only
python balance_check.py
Return the maximum width of a binary tree, meaning the largest number of nodes on any one level. Explain how the answer differs for a skewed tree versus a complete tree, and what the queue holds at its peak.
Sample Answer
The idea
The width of a level is just how many nodes sit at that depth. Depth is counted in edges (the links between a parent and a child), so the root is at depth 0; heights follow the same rule, with an empty tree at -1 and a single node at 0. Maximum width is the largest of those counts over all depths.
Breadth-first search (BFS: visit the tree level by level using a queue, a first-in first-out line) hands you each count for free. At the moment a level starts, the queue contains exactly that level, so len(queue) is its width. Take the maximum of those lengths. Nothing about empty child slots matters here: only real nodes are counted, so null gaps between nodes do not add to the width.
1 depth 0: width 1
/ \
2 3 depth 1: width 2
/ \ \
4 5 6 depth 2: width 3 <- maximum
Approach
- Empty tree: width 0.
- Start with the root in a
deque(a double-ended queue with O(1) pops at the front). - For each level, read
size = len(queue), update the best width, pop exactlysizenodes and push their children. - Track the largest queue length seen after any push, to answer what the queue holds at its peak.
A depth-first version keeps counts[depth] and increments it as each node is reached, then returns max(counts); it is included as a cross-check.
Code
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def max_width(root, trace=False):
"""Largest number of nodes on one level, plus the biggest queue ever seen."""
if root is None:
return 0, 0
queue, widest, peak, depth = deque([root]), 0, 1, 0
while queue:
size = len(queue)
widest = max(widest, size)
for _ in range(size):
node = queue.popleft()
for child in (node.left, node.right):
if child:
queue.append(child)
peak = max(peak, len(queue))
if trace:
print(f"depth {depth}: width {size}, queue after level {len(queue)}")
depth += 1
return widest, peak
def max_width_dfs(root):
counts = []
def walk(node, depth):
if node is None:
return
if depth == len(counts):
counts.append(0)
counts[depth] += 1
walk(node.left, depth + 1)
walk(node.right, depth + 1)
walk(root, 0)
return max(counts, default=0)
def perfect(height):
"""Perfect tree with 2^(height+1) - 1 nodes; height counts edges."""
level = [Node(0)]
root = level[0]
for _ in range(height):
nxt = []
for n in level:
n.left, n.right = Node(0), Node(0)
nxt += [n.left, n.right]
level = nxt
return root
def chain(n):
root = tail = Node(0)
for _ in range(n - 1):
tail.left = Node(0) # every node has only a left child
tail = tail.left
return root
# 1
# / \
# 2 3 widths by depth: 1, 2, 3
# / \ \
# 4 5 6
t = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(max_width(t, trace=True))
print("height nodes width peak queue")
for h in range(5):
t = perfect(h)
w, p = max_width(t)
print(f"{h:>6} {2 ** (h + 1) - 1:>6} {w:>6} {p:>6}")
# 1
# / \
# 2 3 widths by depth: 1, 2, 3, 2
# / \ \
# 4 5 6
# / \
# 7 8
t = Node(1, Node(2, Node(4, Node(7), Node(8)), Node(5)), Node(3, None, Node(6)))
print("widths 1, 2, 3, 2:", max_width(t))
print("chain of 1000:", max_width(chain(1000)))
print("empty:", max_width(None))
try:
max_width_dfs(chain(5000))
except RecursionError:
print("recursive version: RecursionError on a 5000-node chain")
print("queue version on the same chain:", max_width(chain(5000)))
import random
def random_tree(rng, n):
root = Node(0)
nodes = [root]
for _ in range(n - 1):
parent = rng.choice(nodes)
side = rng.choice(["left", "right"])
if getattr(parent, side) is None:
child = Node(0)
setattr(parent, side, child)
nodes.append(child)
return root
def depth_of_all(root):
out, stack = [], [(root, 0)]
while stack:
node, d = stack.pop()
out.append(d)
stack += [(c, d + 1) for c in (node.left, node.right) if c]
return out
rng = random.Random(41)
for _ in range(500):
t = random_tree(rng, rng.randint(1, 40))
depths = depth_of_all(t)
expected = max(depths.count(d) for d in set(depths))
w, p = max_width(t)
assert w == max_width_dfs(t) == expected
assert w <= p <= 2 * w
print("500 random trees: widths agree and width <= peak queue <= 2 * width")
Output
depth 0: width 1, queue after level 2
depth 1: width 2, queue after level 3
depth 2: width 3, queue after level 0
(3, 3)
height nodes width peak queue
0 1 1 1
1 3 2 2
2 7 4 4
3 15 8 8
4 31 16 16
widths 1, 2, 3, 2: (3, 4)
chain of 1000: (1, 1)
empty: (0, 0)
recursive version: RecursionError on a 5000-node chain
queue version on the same chain: (1, 1)
500 random trees: widths agree and width <= peak queue <= 2 * width
Worked trace
The first three lines are the trace for the drawn tree. Depth 0: the queue holds [1] (width 1); popping it pushes 2 and 3, so 2 nodes wait. Depth 1: width 2; popping 2 pushes 4 and 5, popping 3 pushes 6, so 3 nodes wait. Depth 2: width 3; the three leaves push nothing and the queue empties. The largest count is 3, and the largest queue size was also 3, so the function returns (3, 3).
Skewed tree versus perfect tree
- Skewed tree (every node has one child, a chain): every level holds one node, so the width is 1 whatever n is, and the queue never holds more than 1 node (the output line
chain of 1000prints(1, 1)). Space is O(1) beyond the call itself. - Perfect tree (every level full): level d holds 2^d nodes, so the last level of a tree with n nodes holds (n + 1) / 2 of them. The table shows widths 1, 2, 4, 8, 16 for heights 0 to 4, with n = 1, 3, 7, 15, 31. The width is about half of all the nodes, so the answer grows linearly with n.
- What the queue holds at its peak: only nodes from two neighbouring levels are ever in the queue together (the unprocessed rest of level d and the children already pushed from level d + 1). So the peak is never more than the sum of two adjacent widths, hence at most twice the maximum width, and never less than the maximum width because every full level sits in the queue at once. On a perfect tree the peak equals the final level, (n + 1) / 2 nodes (the table prints equal "width" and "peak" columns); on a chain it is 1. The peak can be larger than the width: in the tree with widths 1, 2, 3, 2 the run prints
(3, 4), because once node 4 is popped the queue holds 5 and 6 (the rest of depth 2) together with 7 and 8 (the children just pushed from depth 3), which is four nodes although no depth has more than three.
Complexity
- Time O(n): every node is pushed once and popped once.
- Space O(w) for the queue, where w is the maximum width: O(1) on a chain, O(n) on a perfect tree.
- DFS cross-check: O(n) time and O(h) space (call stack plus the
countslist), where h is the height in edges. That is O(log n) on a perfect tree but O(n) on a chain, so DFS is the smaller of the two on wide, shallow trees and the larger on tall, thin ones.
Edge cases and common mistakes
- Empty tree returns 0; one node returns 1.
- Recursion limit: the recursive DFS raises
RecursionErroron a 5000-node chain, because CPython's default limit is 1000 nested calls; the queue version handles it, which the output shows. - Looping
while queuefor the inner loop instead of popping exactlysizenodes runs every level together: on the drawn tree the width comes out as 1 instead of 3, because only the queue length at the start of the first level is ever recorded. - Counting
Nonechildren as queue entries (pushing them) inflates the width; push only real nodes. - A neighbouring problem measures the span between the leftmost and rightmost node of a level, counting the empty slots between them by position. That is a different quantity from the node count asked for here, and it needs position numbers instead of a plain count.
The assert block checks the queue version against the DFS version and an independent depth count on 500 random trees (fixed seed), and checks that width <= peak <= 2 x width on each.
Running the code
Save as max_width.py and run python3 max_width.py (Python 3.12, standard library only).
Invert a binary tree by swapping the left and right children of every node. Do it recursively and iteratively, and say which you would ship when trees can be very deep.
Sample Answer
The idea in plain words
Inverting a binary tree means producing its mirror image: at every node the left and right children trade places, with their whole subtrees riding along. The key insight is that the swap at one node does not depend on any other node. Swapping the two child pointers of a node moves two entire subtrees at once, and each of those subtrees still has to be mirrored inside itself, so the only requirement is that every node gets swapped exactly once, in any order.
Height convention: height counts edges, so an empty tree has height -1 and a single node has height 0.
Before: After:
1 1
/ \ / \
2 3 3 2
/ \ \ / / \
4 5 6 6 5 4
Two ways to do it
Recursive. For a node, invert the right subtree and the left subtree, then attach them to the opposite sides. The base case is the empty tree (return None). The two recursive calls are finished before the assignment takes place, because a Python tuple assignment evaluates its whole right-hand side first.
Iterative. Keep an explicit stack (a list where the newest item comes off first) of nodes still to be swapped. Pop a node, swap its two children, and push the children that exist. No node is pushed before its parent has been popped, and each node is popped once, so every node is swapped exactly once. A queue works equally well, since the order of visits does not matter for correctness.
Code
import random
import sys
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def invert_recursive(node):
"""Swap the children of every node, in place. Returns the same root."""
if node is None:
return None
# Both recursive calls finish before the two assignments happen.
node.left, node.right = invert_recursive(node.right), invert_recursive(node.left)
return node
def invert_iterative(root, on_step=None):
"""Same result with an explicit stack: the swap at one node never depends on another."""
stack = [root] if root else []
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
if on_step:
on_step(node)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return root
def level_order(root):
"""Values level by level, None for a missing child, trailing Nones dropped."""
out, queue = [], deque([root])
while queue:
node = queue.popleft()
if node is None:
out.append(None)
else:
out.append(node.val)
queue.append(node.left)
queue.append(node.right)
while out and out[-1] is None:
out.pop()
return out
def build_example():
# 1
# / \
# 2 3
# / \ \
# 4 5 6
return Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
tree = build_example()
print("before: ", level_order(tree))
invert_iterative(tree, on_step=lambda n: print(
f" swapped at {n.val}: left={n.left.val if n.left else None}, "
f"right={n.right.val if n.right else None}"))
print("iterative:", level_order(tree))
print("recursive:", level_order(invert_recursive(build_example())))
print("empty:", invert_iterative(None), " single node:", level_order(invert_iterative(Node(7))))
# Check both against a mirrored tuple copy, and that inverting twice restores the tree.
def as_tuple(node):
return None if node is None else (node.val, as_tuple(node.left), as_tuple(node.right))
def mirrored(t):
return None if t is None else (t[0], mirrored(t[2]), mirrored(t[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))
rng = random.Random(0)
for _ in range(500):
seed = rng.randrange(10**9)
original = as_tuple(random_tree(random.Random(seed), 12))
for invert in (invert_recursive, invert_iterative):
t = random_tree(random.Random(seed), 12)
invert(t)
assert as_tuple(t) == mirrored(original)
invert(t)
assert as_tuple(t) == original
print("500 random trees: both versions give the mirrored tree, and twice restores it")
# A left-leaning chain of 100000 nodes.
chain = None
for v in range(100000):
chain = Node(v, left=chain)
invert_iterative(chain)
print("iterative on a 100000-node chain: the chain now leans right:",
chain.left is None and chain.right is not None)
invert_iterative(chain)
try:
invert_recursive(chain)
except RecursionError:
print("recursive on the same chain: RecursionError (limit", sys.getrecursionlimit(), ")")
sys.setrecursionlimit(1_000_000)
invert_recursive(chain)
print("recursive after setrecursionlimit(1000000): finished")
Run in a python:3.12 container, it prints:
before: [1, 2, 3, 4, 5, None, 6]
swapped at 1: left=3, right=2
swapped at 2: left=5, right=4
swapped at 4: left=None, right=None
swapped at 5: left=None, right=None
swapped at 3: left=6, right=None
swapped at 6: left=None, right=None
iterative: [1, 3, 2, 6, None, 5, 4]
recursive: [1, 3, 2, 6, None, 5, 4]
empty: None single node: [7]
500 random trees: both versions give the mirrored tree, and twice restores it
iterative on a 100000-node chain: the chain now leans right: True
recursive on the same chain: RecursionError (limit 1000 )
recursive after setrecursionlimit(1000000): finished
Reading the trace
The trace lists nodes in the order they are popped. At 1 the children 2 and 3 trade places, so 3 is now on the left. The stack then holds 3 and 2, with 2 on top: at 2, the children 4 and 5 trade places (5 left, 4 right); the leaves 4 and 5 swap two missing children, which changes nothing. At 3, which had only a right child 6, the swap moves 6 to the left side and leaves the right side empty. The level-order listing confirms the result: [1, 3, 2, 6, None, 5, 4], where None marks a missing child.
Which to ship when trees can be very deep
Ship the iterative version.
- Time and space are the same order for both: O(n) time (each node is handled once), and O(h) extra space for the traversal stack, where h is the height. A chain makes h equal to n - 1.
- The recursive version is limited by CPython's recursion limit, 1000 frames by default. On the 100000-node chain it raises
RecursionError, while the iterative version finishes. - Raising the limit with
sys.setrecursionlimitmakes the recursive version finish in this run, but it is a process-wide setting, and the Python documentation warns that a limit set too high can lead to a crash. A service inverting trees it does not control should not depend on that. - Use the recursive version when the depth is bounded by construction, for example a tree kept balanced, where h is about log2(n). It is shorter and clearer.
- A queue-based version holds up to two neighbouring levels at once, about n / 2 nodes on a perfect tree, so the stack is the better choice on memory too.
Complexity
- Time O(n): one swap per node.
- Extra space O(h) for the stack or the call frames, from O(log n) on a balanced tree to O(n) on a chain.
- Both versions change the tree in place. If the original must be kept, build a new tree by creating a node for every original node with its two children taken in the opposite order; that costs O(n) additional memory.
Edge cases and common mistakes
- Empty tree: the iterative version returns
Nonewithout touching anything. A single node stays the same. - Swapping only at the root or only the leaves is a frequent mistake. Every node, including those with one child, must be swapped.
- Swapping a node's children but then continuing into only one of them leaves the other subtree un-inverted. Both subtrees need the same treatment.
- Inverting twice restores the original tree, which makes a handy test; the check in the code does it with 500 random trees.
Running the code
Save the listing as invert_tree.py and run it with Python 3.12. It uses only the standard library, so there is nothing to install.
python3 invert_tree.py
Why does an inorder traversal of a binary search tree come out sorted? State the invariant, argue it by induction on the subtrees, and say what changes when duplicate keys are allowed.
Sample Answer
The idea in plain words
A binary search tree (BST) is a binary tree with one rule at every node: everything in its left subtree is smaller than the node, and everything in its right subtree is larger (or equal, depending on how duplicates are handled, covered below). Inorder traversal visits the left subtree, then the node, then the right subtree. Because the rule says the left side is all smaller and the right side is all larger, visiting "left, node, right" produces "smaller stuff, this key, larger stuff", and the same argument applies inside each subtree. That is the whole reason the output is sorted.
The invariant
An invariant is a statement that stays true at all times. The BST invariant, for every node x in the tree, is:
- every key in x's left subtree is less than x.key, and
- every key in x's right subtree is greater than or equal to x.key (the convention used here: ties go right).
Note the word "every", not "the child". Comparing a node only with its direct children is not enough, as the code below shows.
Proof by induction on the number of nodes
Induction proves a claim for trees of every size by two moves: show it for the smallest tree (the base case), then show that if it holds for every tree with fewer nodes (the assumption, called the induction hypothesis) it must hold for the tree in hand (the inductive step). Claim: for every BST T, the list inorder(T) is sorted in non-decreasing order (each key at least the one before it, so [2, 2, 5] qualifies; strictly increasing, with no repeats, when all keys are distinct).
- Base case, the empty tree: inorder is the empty list, which is trivially sorted. (A single node gives a one-element list, also sorted.)
- Inductive step: suppose the claim holds for every BST with fewer nodes than T. Let T have root r with left subtree L and right subtree R, so inorder(T) = inorder(L), then r.key, then inorder(R).
- L and R are themselves BSTs, because the invariant is a statement about each node and its descendants, and descendants of a node in L are the same nodes in L. They have fewer nodes than T, so by the hypothesis inorder(L) and inorder(R) are each sorted.
- Every element of inorder(L) is less than r.key, by the invariant at r. So the sorted block L is followed correctly by r.key.
- Every element of inorder(R) is greater than or equal to r.key, by the invariant at r. So r.key is followed correctly by the sorted block R.
- A sorted block, then a key at least as large as all of it, then a sorted block whose elements are all at least that key, is a sorted list.
- By induction the claim holds for every BST.
Code that checks it
import random
class Node:
def __init__(self, key):
self.key, self.left, self.right = key, None, None
def insert(root, key):
"""Duplicates go to the right subtree."""
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
def inorder(node, out=None):
out = [] if out is None else out
if node is not None:
inorder(node.left, out)
out.append(node.key)
inorder(node.right, out)
return out
def build(keys):
root = None
for k in keys:
root = insert(root, k)
return root
print("distinct :", inorder(build([5, 2, 8, 1, 3, 6, 9])))
print("duplicates:", inorder(build([5, 2, 5, 8, 5, 2])))
# Every parent satisfies "left child < parent < right child", yet the tree is not a BST:
# 5
# /
# 3
# \
# 6 6 sits in the left subtree of 5 but is larger than 5
bad = Node(5)
bad.left = Node(3)
bad.left.right = Node(6)
print("local-rule-only tree:", inorder(bad))
random.seed(7)
for _ in range(300):
keys = [random.randint(0, 20) for _ in range(random.randint(0, 15))]
assert inorder(build(keys)) == sorted(keys)
print("300 random insert sequences: all inorder results equal sorted(keys)")
Output:
distinct : [1, 2, 3, 5, 6, 8, 9]
duplicates: [2, 2, 5, 5, 5, 8]
local-rule-only tree: [3, 6, 5]
300 random insert sequences: all inorder results equal sorted(keys)
What the output shows:
- Distinct keys inserted as 5, 2, 8, 1, 3, 6, 9 come out as
[1, 2, 3, 5, 6, 8, 9]. - The tree used for the local-rule example is:
5
/
3
\
6
Each parent-child pair looks fine (3 is less than 5, and 6 is greater than 3), but 6 sits in the left subtree of 5 and is larger than 5. The invariant is broken and inorder gives [3, 6, 5], not sorted. This is why a BST validity check that compares only a node with its immediate children is wrong.
- The last line comes from an
assertover 300 random insertion sequences, with duplicates, that compares the inorder list withsorted(keys).
What changes when duplicate keys are allowed
- With one fixed side for ties (here: equal goes right), the invariant becomes "left strictly less, right greater or equal". The proof above goes through unchanged and the result is non-decreasing: the output
[2, 2, 5, 5, 5, 8]for the keys 5, 2, 5, 8, 5, 2 shows equal keys adjacent in the inorder list. - It is "non-decreasing", not "strictly increasing", so a validity check that uses
<between consecutive inorder values wrongly rejects trees with duplicates; it needs<=. - If equal keys may go to either side, the proof still works with
<=on both sides, but a search for all copies of a key can no longer stop at the first one: equal keys can be in both subtrees. With one fixed side the search knows where to look next: after a match it keeps walking to the tie side. With both sides allowed it would have to explore both subtrees below every match, which can mean visiting the whole tree. - The chosen side must be applied consistently everywhere. A rebalancing rotation can move an equal key to the other side (a right-leaning chain of three equal keys rotated into a balanced shape puts one equal key in a left subtree), which silently breaks a "ties go right" rule. The next section pictures a rotation and runs it.
- The usual alternatives are to keep a count in each node or a list of values per key, so each key appears once in the tree.
A rotation, with numbers
A rotation is a local rearrangement of a few pointers that changes which node is on top while keeping the inorder order of the nodes. A left rotation at x takes x's right child y, makes y the top, makes x the left child of y, and hands y's old left subtree to x as its new right subtree. Self-balancing trees such as AVL and red-black trees (trees that rotate nodes after inserts and deletes to keep the height near log2(n)) are built from this move, and a coding interview typically needs only the fact that a rotation keeps the inorder order and, for distinct keys, the BST rule. Writing a full AVL or red-black insert from memory is deeper material than a typical interview round asks for.
Three equal keys inserted with ties going right form a chain, and a left rotation at the top turns the chain into a balanced shape:
5A 5B
\ / \
5B -> 5A 5C
\
5C
The letters A, B, C only record insertion order so the equal keys can be told apart. The program below inserts a tie to show the rule, builds the chain, rotates it, and then runs a search for all copies that follows the ties-go-right rule. Its printed output follows the code.
class Node:
def __init__(self, key, tag):
self.key, self.tag = key, tag # tag tells equal keys apart: A, B, C = insertion order
self.left = self.right = None
def insert(root, key, tag):
"""Ties go right: left subtree < node <= right subtree."""
if root is None:
return Node(key, tag)
if key < root.key:
root.left = insert(root.left, key, tag)
else:
root.right = insert(root.right, key, tag)
return root
def shape(node):
"""(key+tag, left, right) with None for an empty side."""
return None if node is None else (f"{node.key}{node.tag}", shape(node.left), shape(node.right))
def inorder_tags(node):
return [] if node is None else inorder_tags(node.left) + [f"{node.key}{node.tag}"] + inorder_tags(node.right)
def rotate_left(x):
"""x's right child y becomes the top; x becomes y's left child; y's old left subtree moves
to become x's right subtree. Only three pointers change."""
y = x.right
x.right = y.left
y.left = x
return y
# 1. Ties go right, on a concrete tie: the second 5 is not smaller than the root 5, so it goes right.
root = None
for key, tag in ((5, "A"), (2, "x"), (5, "B")):
root = insert(root, key, tag)
print("insert 5, 2, 5 (ties go right):", shape(root))
# 2. Three equal keys form a right-leaning chain.
root = None
for tag in "ABC":
root = insert(root, 5, tag)
print("chain of three 5s:", shape(root))
print("inorder:", inorder_tags(root))
# 3. A left rotation at the root rebalances it, and keeps the inorder order of the three nodes.
root = rotate_left(root)
print("after rotate_left:", shape(root))
print("inorder:", inorder_tags(root))
print("left subtree of the new root holds an equal key:", root.left.key == root.key)
# 4. A search for all copies that obeys 'ties go right' keeps walking right after each hit.
def count_copies_ties_right(node, key):
found = 0
while node:
if key == node.key:
found += 1
node = node.right
else:
node = node.left if key < node.key else node.right
return found
print("copies of 5 stored: 3 | found by the ties-right search:", count_copies_ties_right(root, 5))
insert 5, 2, 5 (ties go right): ('5A', ('2x', None, None), ('5B', None, None))
chain of three 5s: ('5A', None, ('5B', None, ('5C', None, None)))
inorder: ['5A', '5B', '5C']
after rotate_left: ('5B', ('5A', None, None), ('5C', None, None))
inorder: ['5A', '5B', '5C']
left subtree of the new root holds an equal key: True
copies of 5 stored: 3 | found by the ties-right search: 2
Reading it: the first line shows the second 5 (5B) going to the right of the root 5 (5A), not the left, because it is not smaller. The inorder list is ['5A', '5B', '5C'] both before and after the rotation, so the sorted order survives. The rotated tree has 5A in the left subtree of 5B, an equal key on the left, which breaks "left strictly less". The ties-right search then walks from the new root 5B to the right and finds 5B and 5C: 2 of the 3 copies, and 5A is missed. A rule such as "equal keys may be in either subtree" is what a balanced tree has to adopt, which is why such trees usually store a count per key or use distinct keys.
Complexity of the check
insert is O(h) per key, for height h of the tree (the longest root-to-leaf path), and inorder visits each node once with an appended list, so O(n) time and O(h) recursion space plus O(n) for the output. Building the tree from sorted input gives a chain with h = n - 1, which also means a recursion depth near n and a RecursionError past about 1000 nodes in CPython.
Common mistakes
- Verifying only parent versus child, which the 5, 3, 6 tree defeats.
- Reading the result backwards, as if the sorted list identified the tree (the converse is a different statement from the theorem: the theorem says a BST gives a sorted list, and it does not say that a sorted list gives back one particular BST). A sorted inorder list does not tell you the shape: the keys 1, 2, 3 form a valid BST as a chain or as a balanced tree, and both give the same inorder list.
- Using strict inequality on both sides and then having no place to put a duplicate.
Running the code
Save the first code block as bst_inorder.py and the rotation program as rotation.py, then run python3 bst_inorder.py and python3 rotation.py with Python 3.12. Only the standard library (random) is used, by the first one.
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.