A tree is a hierarchical data structure made of nodes connected by edges, with one special node called the root and no cycles. Every node except the root has exactly one parent, and a node can have any number of children. Formally, a tree with n nodes is a connected, acyclic graph and always has exactly n − 1 edges, so there is exactly one path between any two nodes.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Terminology
Term
Meaning
Root
The top node; it has no parent
Parent, child
A node directly above or below another along an edge
Siblings
Nodes with the same parent
Leaf
A node with no children
Internal node
A node with at least one child
Degree of a node
Number of children it has
Depth of a node
Number of edges from the root to that node (the root has depth 0)
Height of a node
Number of edges on the longest path from that node down to a leaf
Height of a tree
Height of the root (a single node has height 0; an empty tree is often defined as −1)
Level
All nodes at the same depth
Subtree
A node together with all its descendants
Ancestor, descendant
Nodes on the path above, or anywhere below, a node
Small Example
A depth 0
/ | \
B C D depth 1
/ \ \
E F G depth 2
Root A; leaves E, F, C, G; internal nodes A, B, D.
7 nodes and 6 edges, as n − 1 predicts.
Height of the tree is 2; the degree of A is 3.
The subtree rooted at B is {B, E, F}.
Key Properties
Unique paths: exactly one simple path between any two nodes, so there is no need for a visited set when walking down from the root.
Recursive structure: each child is the root of its own subtree, which is why many tree algorithms are naturally recursive.
Adding any edge creates a cycle; removing any edge disconnects it.
Common Tree Families
Family
Rule
Typical use
General (n-ary) tree
Any number of children
File systems, DOM, org charts
Binary tree
At most two children
Expression trees, heaps
Binary search tree
Left subtree smaller, right larger
Ordered maps and sets
AVL and red-black trees
Self-balancing BSTs
Guaranteed O(log n) lookups
B-tree and B+ tree
Many keys per node, all leaves at one depth
Database indexes, file systems
Heap
Parent ordered relative to children
Priority queues
Segment and Fenwick trees
Store aggregates over ranges
Range queries
Trie
Edges labelled by characters
Prefix search
Why Trees Are Used
Hierarchies are natural trees: folders, categories, HTML elements, company structures.
Fast ordered search: a balanced search tree finds, inserts and deletes in O(log n), compared with O(n) for an unsorted list.
Range and prefix queries that hash tables cannot answer efficiently.
Parsing: compilers turn source code into abstract syntax trees.
Complexity Notes
For a tree of height h, walking from the root to a node costs O(h) time. Visiting every node (any traversal) costs O(n) time, with O(h) extra space for a recursive depth-first traversal (the recursion stack) or O(w) for breadth-first, where w is the widest level. The tree itself uses O(n) space. Height ranges from about log₂ n for a balanced binary tree to n − 1 for a degenerate one, which is why balance matters.
Interview Tips
Define depth and height precisely and state your convention (edges versus nodes); interviewers often check this.
Remember n − 1 edges: it is the quickest test for whether a connected graph is a tree.
Common follow-ups: the difference between a tree and a graph, what makes a binary search tree, and why an unbalanced BST degrades to O(n).
A frequent mistake is calling any hierarchy with shared children a tree; once a node has two parents it is a directed acyclic graph, not a tree.
2
What is a Binary Tree?
KnownRevise
A binary tree is a tree in which every node has at most two children, called the left child and the right child. The left/right distinction matters: a node with only a left child is a different tree from the same node with only a right child. Binary trees are the basis of binary search trees, heaps, expression trees and Huffman codes.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Structure
Each node stores a value and two references, either of which may be empty (None). An empty tree is also a valid binary tree, which makes recursive definitions simple: a binary tree is either empty, or a root with a left binary tree and a right binary tree.
Types
Type
Rule
Full (proper)
Every node has 0 or 2 children
Complete
Every level is full except possibly the last, which is filled from the left
Perfect
All internal nodes have 2 children and all leaves are at the same depth
Balanced
For every node, left and right subtree heights differ by at most 1 (one common definition)
Degenerate
Every internal node has one child; behaves like a linked list
Properties
With height h (edges) and n nodes:
Level d holds at most 2^d nodes.
A tree of height h has at most 2^(h+1) − 1 nodes (a perfect tree).
The minimum possible height for n nodes is ⌊log₂ n⌋; the maximum is n − 1.
In a full binary tree, leaves = internal nodes + 1.
A binary tree with n nodes has n + 1 empty child slots.
Representations
Linked nodes: the usual choice; flexible for any shape.
Array (level order): for complete trees such as heaps. The node at index i has children at 2i + 1 and 2i + 2 and its parent at (i − 1) // 2. Sparse trees waste space in an array.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class TreeNode:
value: int
left: TreeNode | None = None
right: TreeNode | None = None
def build_from_level_order(values: list[int | None]) -> TreeNode | None:
"""Build a binary tree from level-order values where None marks a missing child."""
if not values or values[0] is None:
return None
root = TreeNode(values[0])
queue: deque[TreeNode] = deque([root])
i = 1
while queue and i < len(values):
node = queue.popleft()
if i < len(values) and values[i] is not None:
node.left = TreeNode(values[i])
queue.append(node.left)
i += 1
if i < len(values) and values[i] is not None:
node.right = TreeNode(values[i])
queue.append(node.right)
i += 1
return root
def count_nodes_and_leaves(root: TreeNode | None) -> tuple[int, int]:
"""Return (number of nodes, number of leaves) using an explicit stack."""
nodes = leaves = 0
stack = [root] if root else []
while stack:
node = stack.pop()
nodes += 1
if node.left is None and node.right is None:
leaves += 1
for child in (node.left, node.right):
if child:
stack.append(child)
return nodes, leaves
tree = build_from_level_order([1, 2, 3, 4, None, 5, 6])
print(count_nodes_and_leaves(tree)) # (6, 3)
Walkthrough
[1, 2, 3, 4, None, 5, 6] builds:
1
/ \
2 3
/ / \
4 5 6
Six nodes; leaves 4, 5, 6. Node 2 has only a left child, so the tree is not full, and the gap after 4 on the last level means it is not complete either.
Complexity
Building and counting both visit each node once: O(n) time. Extra space is O(w) for the queue (widest level) or O(h) for the stack, where h can be n − 1 for a degenerate tree; the tree itself is O(n). The iterative stack avoids Python’s recursion limit (about 1,000) on deep, skewed trees.
Edge Cases
Empty input returns None and counts (0, 0).
A single node is both the root and a leaf.
Duplicates and negative values are allowed; a plain binary tree has no ordering rule.
A degenerate tree has height n − 1, so recursive algorithms can overflow the stack.
Common Pitfalls
Confusing a binary tree with a binary search tree; only the latter orders values.
Mixing up complete, full and perfect.
Assuming height log n for every binary tree; that holds only when it is balanced.
Interviewers usually follow up with traversals (inorder, preorder, postorder, level order) or with computing height and checking balance.
3
Explain Height and Depths in the context of a Tree.
KnownRevise
Depth measures how far a node is from the root: the number of edges on the path from the root down to it, so the root has depth 0. Height measures how far a node is from the bottom: the number of edges on the longest path from that node down to a leaf, so every leaf has height 0. The height of the tree is the height of its root, which equals the maximum depth of any node.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Definitions and Conventions
Term
Measured from
Root
Leaf
Empty tree
Depth of a node
The root, downward
0
Varies
Not defined
Height of a node
The node, down to its deepest leaf
Height of the tree
0
−1 (common convention)
Level
Same as depth (some texts start at 1)
0 or 1
Varies
Not defined
Some books count nodes instead of edges, making a single-node tree height 1. Both are used; state the convention in an interview. This answer counts edges.
Example
A depth 0, height 3
/ \
B C depth 1; height of B = 2, height of C = 0
/ \
D E depth 2; height of D = 1, height of E = 0
/
F depth 3, height 0
Tree height = height of A = 3 = depth of the deepest node F.
C is shallow (depth 1) and also a leaf (height 0).
Recurrences
depth(root) = 0, and depth(child) = depth(parent) + 1. Depth is computed top-down.
height(empty) = −1, and height(node) = 1 + max(height(left), height(right)). Height is computed bottom-up.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class TreeNode:
value: str
left: TreeNode | None = None
right: TreeNode | None = None
def tree_height(root: TreeNode | None) -> int:
"""Height in edges via level-order traversal; -1 for an empty tree."""
if root is None:
return -1
height = -1
queue: deque[TreeNode] = deque([root])
while queue:
height += 1
for _ in range(len(queue)):
node = queue.popleft()
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return height
def node_depths(root: TreeNode | None) -> dict[str, int]:
"""Map each node's value to its depth using an explicit stack."""
depths: dict[str, int] = {}
stack = [(root, 0)] if root else []
while stack:
node, depth = stack.pop()
depths[node.value] = depth
for child in (node.right, node.left):
if child:
stack.append((child, depth + 1))
return depths
f = TreeNode("F")
root = TreeNode("A", TreeNode("B", TreeNode("D", f), TreeNode("E")), TreeNode("C"))
print(tree_height(root)) # 3
print(node_depths(root)) # {'A': 0, 'B': 1, 'D': 2, 'F': 3, 'E': 2, 'C': 1}
Walkthrough of tree_height
Level processed
Queue before
Height after
0
[A]
0
1
[B, C]
1
2
[D, E]
2
3
[F]
3
Complexity
Both functions visit every node once: O(n) time. Extra space is O(w) for the queue, where w is the widest level (up to about n/2 in a perfect tree), and O(h) for the depth stack; the output dictionary is O(n). The recursive height version uses O(h) call-stack space, and h can reach n − 1 in a degenerate tree, so the iterative versions avoid Python’s recursion limit.
Why They Matter
BST, AVL and red-black operations cost O(h), so keeping height near log₂ n keeps them fast.
AVL trees store each node’s height to compute the balance factor height(left) − height(right).
B-trees keep every leaf at the same depth, which bounds disk reads.
Algorithms such as lowest common ancestor use depth to lift nodes to the same level.
Edge Cases
Empty tree: height −1 by this convention (or 0 if counting nodes).
Single node: height 0, depth 0.
Skewed tree: height n − 1.
Duplicate values: the depth dictionary above keys by value, so duplicates would overwrite each other; key by node identity in real code.
Interview Tips
Say “depth goes down from the root, height goes up from the leaves”, and state edges or nodes.
A common follow-up is computing the height or checking whether a tree is balanced in one pass.
A frequent off-by-one error is returning 0 for an empty tree in an edge-counting solution, which makes every height one too small.
4
What is the difference between a Tree and a Graph?
KnownRevise
A tree is a special kind of graph: an undirected graph that is connected and has no cycles. A tree with n nodes always has exactly n − 1 edges and exactly one path between any two nodes, and usually has a designated root that gives it a parent-child hierarchy. A general graph has no such limits: it can have cycles, several components, any number of edges, directed or weighted edges, and nodes with many “parents”.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Tree
Graph
Cycles
None
Allowed
Connectivity
Always connected
May have several components
Edges for n nodes
Exactly n − 1
0 to n(n − 1)/2 undirected (more with multi-edges)
A forest is a graph whose components are all trees. A directed acyclic graph (DAG) has no cycles but allows a node to have several parents, so it is not a tree.
Checking Whether a Graph Is a Tree
An undirected graph with n nodes is a tree exactly when it has n − 1 edges and is connected (equivalently, n − 1 edges and no cycle). Union-find checks for a cycle while counting components:
Code Example
def is_tree(node_count: int, edges: list[tuple[int, int]]) -> bool:
"""Return True if the undirected graph on nodes 0..node_count-1 is a tree."""
if node_count == 0:
return False
if len(edges) != node_count - 1:
return False
parent = list(range(node_count))
def find(node: int) -> int:
while parent[node] != node:
parent[node] = parent[parent[node]] # path halving
node = parent[node]
return node
for left, right in edges:
root_left, root_right = find(left), find(right)
if root_left == root_right:
return False # this edge closes a cycle
parent[root_left] = root_right
return True # n-1 edges and no cycle implies connected
print(is_tree(5, [(0, 1), (0, 2), (0, 3), (1, 4)])) # True
print(is_tree(5, [(0, 1), (1, 2), (2, 3), (1, 3)])) # False
print(is_tree(4, [(0, 1), (2, 3), (1, 2)])) # True
Walkthrough
Second example, n = 5, edges (0,1) (1,2) (2,3) (1,3):
Edge
Roots
Action
(0, 1)
0, 1
Union
(1, 2)
1, 2
Union
(2, 3)
2, 3
Union
(1, 3)
same root
Cycle, return False
Node 4 is also isolated, so the graph fails both rules.
Complexity
Time: O(E · α(n)) for union-find with path halving alone, where α is the inverse Ackermann function, which is effectively constant; adding union by rank or size guarantees that bound. Since E = n − 1 once the edge count passes, this is O(n) in practice.
Space: O(n) for the parent array; no recursion. The input edge list is not counted.
A BFS or DFS alternative also runs in O(n + E) time and O(n) space, with a visited set, and must check that every node was reached.
Edge Cases
n = 1 with no edges is a tree (a single root).
n = 0 is treated here as not a tree; some definitions accept the empty tree, so state it.
Self-loops (v, v) and duplicate edges are detected as cycles by union-find.
Disconnected graphs are caught by the edge count: a forest with k components has n − k edges.
When the Difference Matters in Design
Data that is strictly hierarchical (categories, folders) fits a tree; parent pointers and recursive queries are simple.
Once an item can have two parents (a product in two categories, a package used by many others), model it as a DAG or graph and handle shared nodes and cycles explicitly.
Interview Tips
Give the one-line definition: a tree is a connected acyclic graph with n − 1 edges.
A common follow-up is “Graph Valid Tree”, solved exactly as above.
A frequent mistake is checking only the edge count; n − 1 edges can still form a cycle plus an isolated node, so also check for cycles or connectivity.
5
Define Leaf and Internal nodes in a Tree.
KnownRevise
A leaf (external or terminal node) is a node with no children. An internal node is a node with at least one child. Every node in a tree is exactly one of the two. The root is an internal node unless it is the only node in the tree, in which case it is also a leaf.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Example
8
/ \
3 10
/ \ \
1 6 14
/ \
4 7
Leaves:1, 4, 7, 14 (no children).
Internal nodes:8, 3, 10, 6 (one or two children). 10 is internal even though it has only one child.
Useful Properties
Tree type
Relationship
Any tree with n nodes
leaves + internal = n
Full binary tree (0 or 2 children)
leaves = internal + 1
Full k-ary tree (0 or k children)
leaves = (k − 1) × internal + 1
Perfect binary tree of height h
2^h leaves, 2^h − 1 internal
General tree
leaves = 1 + Σ (children − 1) over internal nodes
The last formula follows from counting edges two ways: every node except the root has one parent edge, so n − 1 = Σ children. In the example, internal nodes have 2, 2, 1 and 2 children, so leaves = 1 + (1 + 1 + 0 + 1) = 4.
Where the Distinction Matters
B+ trees store all data records in the leaves and only routing keys in internal nodes.
Huffman trees keep symbols in leaves; internal nodes hold combined weights.
Expression trees have operands in leaves and operators in internal nodes.
Segment trees store array elements in leaves and range aggregates in internal nodes.
Recursive algorithms use the leaf test as a base case (for example, root-to-leaf path sums).
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class TreeNode:
value: int
left: TreeNode | None = None
right: TreeNode | None = None
def classify_nodes(root: TreeNode | None) -> tuple[list[int], list[int]]:
"""Return (leaf values, internal node values) in preorder, using an explicit stack."""
leaves: list[int] = []
internal: list[int] = []
stack = [root] if root else []
while stack:
node = stack.pop()
if node.left is None and node.right is None:
leaves.append(node.value)
else:
internal.append(node.value)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return leaves, internal
root = TreeNode(8,
TreeNode(3, TreeNode(1), TreeNode(6, TreeNode(4), TreeNode(7))),
TreeNode(10, None, TreeNode(14)))
print(classify_nodes(root)) # ([1, 4, 7, 14], [8, 3, 6, 10])
Walkthrough
Step
Popped
Has children?
Leaves
Internal
1
8
yes
8
2
3
yes
8, 3
3
1
no
1
8, 3
4
6
yes
1
8, 3, 6
5
4
no
1, 4
8, 3, 6
6
7
no
1, 4, 7
8, 3, 6
7
10
yes
1, 4, 7
8, 3, 6, 10
8
14
no
1, 4, 7, 14
8, 3, 6, 10
Complexity
Each node is pushed and popped once: O(n) time. The stack holds O(h) nodes for typical shapes and the output lists hold O(n) values; the tree itself is not counted. The explicit stack avoids hitting Python’s recursion limit on a degenerate tree.
Edge Cases
Empty tree: both lists are empty.
Single node: the root is a leaf and there are no internal nodes.
One-child nodes: still internal (10 above).
Duplicates and negative values: classification depends only on children, not values.
Common Pitfalls
Treating a node with one child as a leaf; check both children are missing.
Forgetting the single-node case, where the root is a leaf.
In n-ary trees, test not node.children rather than a fixed pair of fields.
Interviewers often follow up with “count the leaves”, “sum of root-to-leaf paths” or “prove leaves = internal + 1 for a full binary tree” (induction, or the edge-counting argument above).
6
What is a Rooted Tree, and how does it differ from an Unrooted Tree?
KnownRevise
A rooted tree has one node chosen as the root, which gives every edge a direction (parent → child) and every node a depth, a parent and children. An unrooted (free) tree is just a connected acyclic graph: there is no top, no parent-child relationship, only neighbours. Any unrooted tree can be turned into a rooted one by choosing any node as the root; choosing a different root gives a different rooted tree with the same edges.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Rooted tree
Unrooted (free) tree
Special node
One root
None
Relationships
Parent, child, ancestor, descendant, sibling
Neighbours only
Depth, height, level
Defined
Not defined (only distances, eccentricity)
Edge direction
Implied: away from the root
Undirected
Natural representation
Node objects with child lists, or a parent array
Adjacency list
Typical uses
File systems, DOM, BSTs, heaps, org charts
Network topologies, spanning trees, phylogenetic trees without a known ancestor
Both have n − 1 edges and unique paths between nodes; rooting adds structure, not edges.
Rooting an Unrooted Tree
Given an adjacency list, a BFS from the chosen root assigns each node a parent and a depth. Every edge then points from the node reached first to the node reached later.
Code Example
from collections import deque
def root_tree(adjacency: dict[int, list[int]], root: int) -> tuple[dict[int, int | None], dict[int, int]]:
"""Root an undirected tree at `root`; return (parent map, depth map)."""
if root not in adjacency:
raise ValueError("root is not in the tree")
parent: dict[int, int | None] = {root: None}
depth: dict[int, int] = {root: 0}
queue: deque[int] = deque([root])
while queue:
node = queue.popleft()
for neighbour in adjacency[node]:
if neighbour == parent[node]:
continue # do not walk back up the edge we came from
if neighbour in parent:
raise ValueError("graph has a cycle, so it is not a tree")
parent[neighbour] = node
depth[neighbour] = depth[node] + 1
queue.append(neighbour)
if len(parent) != len(adjacency):
raise ValueError("graph is disconnected, so it is not a tree")
return parent, depth
edges = {0: [1, 2], 1: [0, 3, 4], 2: [0], 3: [1], 4: [1]}
print(root_tree(edges, 0)) # ({0: None, 1: 0, 2: 0, 3: 1, 4: 1}, {0: 0, 1: 1, 2: 1, 3: 2, 4: 2})
print(root_tree(edges, 3)[1]) # {3: 0, 1: 1, 0: 2, 4: 2, 2: 3}
Rooted at 0 the height is 2; rooted at 3 it is 3. Leaves and depths change with the root, but the edges do not. Choosing a centre of the tree (a node minimising the longest distance to any other node) as the root gives the minimum possible height.
Complexity
BFS visits each node and each edge twice (once from each end): O(n) time for a tree with n − 1 edges. The parent, depth and queue structures use O(n) space; the input adjacency list is not counted. No recursion is used, so deep paths are safe.
Edge Cases
Single node{0: []}: parent {0: None}, depth {0: 0}.
Disconnected input (a forest): detected because not every node gets a parent.
Cycle: detected when a neighbour other than the parent was already seen.
Duplicate edges or a self-loop: also reported as a cycle; the parent check skips only one copy of the edge back to the parent, so validate inputs if they may contain multi-edges.
Where Each Appears
Rooted: any recursive tree algorithm (subtree sizes, tree DP, LCA) first roots the tree, often at node 0.
Unrooted: minimum spanning trees, network topologies, and phylogenetic trees where the common ancestor is unknown. Biologists often root them with an outgroup or at the midpoint of the longest path.
Interview Tips
Say clearly that rooting is a choice that adds direction and depth to a free tree.
In graph-style tree problems (edges given as pairs), the first step is usually “build an adjacency list and root it with BFS or DFS”.
A common follow-up is “find the root that minimises the tree height” (Minimum Height Trees), solved by repeatedly trimming leaves to find the centre.
A frequent mistake is skipping the parent check in DFS on an undirected tree, which walks back up the edge and reports a false cycle or loops forever.
7
What is a N-ary Tree, and how does it generalize a binary tree?
KnownRevise
An N-ary tree (k-ary, or general tree) is a rooted tree in which a node can have up to N children (or any number, when no bound is fixed). A binary tree is the special case N = 2 with the children named left and right. N-ary trees model hierarchies whose branching is not two: file systems, the HTML DOM, organisation charts, game trees and B-trees.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
What Generalises and What Changes
Aspect
Binary tree
N-ary tree
Children per node
0–2, named left and right
0–N, usually an ordered list
Node fields
left, right
children: list
Inorder traversal
Defined (left, node, right)
No single natural “middle”; preorder, postorder and level order are standard
Max nodes at depth d
2^d
N^d
Max nodes with height h
2^(h+1) − 1
(N^(h+1) − 1) / (N − 1)
Minimum height for n nodes
about log₂ n
about log_N n
Full tree with I internal nodes
2I + 1 nodes, I + 1 leaves
N·I + 1 nodes, (N − 1)·I + 1 leaves
Array layout (complete tree)
children of i at 2i+1, 2i+2
children of i at N·i + 1 … N·i + N
A larger N means a shallower tree. B-trees use this: with hundreds of keys per node, a billion keys fit in a tree only a few levels deep, so a lookup needs only a few disk reads.
Representations
List of children (most common): node.children = [...].
Fixed array of N slots: fast indexing, wasteful when most slots are empty (tries over a fixed alphabet use this).
Left-child right-sibling (LCRS): each node stores its first child and its next sibling, turning any N-ary tree into a binary tree with the same nodes. This shows binary trees can represent any tree.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass, field
@dataclass
class NaryNode:
value: str
children: list[NaryNode] = field(default_factory=list)
@dataclass
class BinaryNode:
value: str
left: BinaryNode | None = None # first child
right: BinaryNode | None = None # next sibling
def level_order(root: NaryNode | None) -> list[list[str]]:
"""Return node values level by level."""
levels: list[list[str]] = []
queue: deque[NaryNode] = deque([root] if root else [])
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft()
level.append(node.value)
queue.extend(node.children)
levels.append(level)
return levels
def to_lcrs(root: NaryNode | None) -> BinaryNode | None:
"""Convert an N-ary tree to its left-child right-sibling binary form, iteratively."""
if root is None:
return None
new_root = BinaryNode(root.value)
stack = [(root, new_root)]
while stack:
original, converted = stack.pop()
previous: BinaryNode | None = None
for child in original.children:
child_copy = BinaryNode(child.value)
if previous is None:
converted.left = child_copy
else:
previous.right = child_copy
previous = child_copy
stack.append((child, child_copy))
return new_root
tree = NaryNode("A", [NaryNode("B", [NaryNode("E"), NaryNode("F")]), NaryNode("C"), NaryNode("D", [NaryNode("G")])])
print(level_order(tree)) # [['A'], ['B', 'C', 'D'], ['E', 'F', 'G']]
binary = to_lcrs(tree)
print(binary.left.value, binary.left.right.value, binary.left.right.right.value) # B C D
Walkthrough of LCRS
N-ary: LCRS (left = first child, right = next sibling):
A A
/ | \ /
B C D B ---- C ---- D
/ \ \ / /
E F G E ---- F G
A‘s first child B becomes its left; C and D hang off B as right siblings.
Complexity
Level order and LCRS conversion each visit every node and edge once: O(n) time. Extra space is O(w) for the queue (widest level) and O(n) for the converted tree; the conversion’s stack is O(n) in the worst case. Both are iterative, so deep trees do not hit Python’s recursion limit.
Edge Cases
Empty tree:[] and None.
Single node: one level; LCRS has no children.
Very wide nodes: the queue can hold most of the tree at once.
Duplicates: fine; nodes are distinct objects even with equal values.
Interview Tips
Say “a binary tree is an N-ary tree with N = 2 and ordered left/right slots”, then mention LCRS to show any tree can be stored as a binary tree.
Common follow-ups: level order, maximum depth, and serialising an N-ary tree.
A frequent mistake is trying to define an inorder traversal for N-ary trees; use preorder, postorder or level order instead.
8
Discuss the properties of a Full Binary Tree.
KnownRevise
A full binary tree (also called a proper or strictly binary tree) is a binary tree in which every node has either 0 or 2 children, never exactly one. That single rule forces tight counting relationships: the number of leaves is always one more than the number of internal nodes, and the total number of nodes is always odd.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Properties
Let I be the number of internal nodes, L the number of leaves, n the total and h the height in edges.
Property
Formula
Leaves versus internal nodes
L = I + 1
Total nodes
n = 2I + 1 = 2L − 1 (always odd)
Edges
n − 1 = 2I (each internal node contributes two)
Maximum nodes for height h
2^(h+1) − 1 (the perfect tree)
Minimum nodes for height h
2h + 1 (one internal node per level, each with a leaf sibling)
Height range for n nodes
from ⌈log₂(n + 1)⌉ − 1 up to (n − 1) / 2
Number of distinct shapes with I internal nodes
Catalan number C(I); for example 5 shapes when I = 3
Why L = I + 1: count edges two ways. Every node except the root has one parent edge, so there are n − 1 = I + L − 1 edges; every internal node has two child edges, so there are 2I edges. Setting them equal gives L = I + 1.
Relation to Other Types
Every perfect binary tree is full, but a full tree need not be perfect (leaves may be at different depths).
A complete binary tree need not be full: its last internal node may have only a left child.
Expression trees with binary operators are full: operators are internal nodes, operands are leaves.
Huffman trees are full, because two subtrees are always merged at once.
Example
+
/ \
* 7
/ \
3 4
I = 2 (+, *), L = 3, n = 5. The expression is (3 * 4) + 7.
The second tree has a * with one child, so it is not full, and the identity L = I + 1 no longer holds (2 leaves, 2 internal nodes).
Complexity
One visit per node: O(n) time. The explicit stack holds O(h) nodes for typical shapes (up to O(n) in the worst case); the tree itself is not counted. No recursion, so degenerate shapes do not hit Python’s recursion limit. Best, average and worst case are the same because every node must be checked; you could stop at the first one-child node if only the yes/no answer is needed.
Edge Cases
Empty tree: conventionally full (no node violates the rule); (True, 0, 0) above.
Single node: full, with I = 0, L = 1.
Even node count: cannot be full, a quick rejection test.
Duplicates and negative values: irrelevant; fullness depends only on shape.
Interview Tips
State the rule (0 or 2 children) and prove L = I + 1 with the edge-counting argument; interviewers like a short proof.
Be ready to distinguish full, complete and perfect with one example each.
A common follow-up is “construct a full binary tree from preorder and postorder traversals”, which is possible precisely because no node has one child.
A frequent mistake is calling a complete tree full; check every node’s child count.
9
What is the significance of the degree of a node in a tree?
KnownRevise
In a rooted tree, the degree of a node is the number of children it has; leaves have degree 0. The degree of the tree is the largest node degree. Degree matters because it sets the branching factor, which decides how tall the tree must be for n nodes, how much memory each node needs, which representation fits, and which invariants a tree family enforces (binary trees allow at most 2, B-trees require between a minimum and maximum).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Two Definitions
Context
Degree of a node
Leaf degree
Sum over all nodes
Rooted tree (data structures)
Number of children
0
n − 1 (each non-root node is one child)
Graph theory (unrooted tree)
Number of neighbours, parent included
1
2(n − 1) (each edge counted at both ends)
State which one you use. This answer uses the rooted definition.
Why It Matters
Aspect
Effect of degree
Height
With maximum degree d, height is at least about log_d n; higher degree gives a shallower tree
Search cost
Each level may scan up to d keys or children; total cost is roughly height × per-node work
Memory
Fixed child arrays cost d pointers per node even when most are empty
Representation
Binary trees use two fields; variable degree needs lists or left-child right-sibling form
Invariants
Binary: ≤ 2. Full binary: 0 or 2. B-tree of order m: internal nodes have between ⌈m/2⌉ and m children (the root at least 2)
Leaf count
leaves = 1 + Σ (degree − 1) over internal nodes
The B-tree case shows the trade-off: a degree in the hundreds keeps a billion-key index only a few levels deep, so a lookup needs only a few disk reads, while each node fits one disk page.
Code Example
from collections import Counter
def degree_profile(children: dict[str, list[str]]) -> tuple[dict[str, int], int, Counter[int]]:
"""Return (degree of each node, degree of the tree, how many nodes have each degree)."""
degrees = {node: len(kids) for node, kids in children.items()}
for kids in children.values():
for kid in kids:
degrees.setdefault(kid, 0) # nodes that appear only as children are leaves
tree_degree = max(degrees.values(), default=0)
histogram = Counter(degrees.values())
return degrees, tree_degree, histogram
tree = {"A": ["B", "C", "D"], "B": ["E", "F"], "D": ["G"]}
degrees, tree_degree, histogram = degree_profile(tree)
print(degrees) # {'A': 3, 'B': 2, 'D': 1, 'C': 0, 'E': 0, 'F': 0, 'G': 0}
print(tree_degree) # 3
print(sum(degrees.values()), len(degrees) - 1) # 6 6
print(histogram[0], 1 + sum(d - 1 for d in degrees.values() if d > 0)) # 4 4
Walkthrough
A degree 3
/ | \
B C D B: 2, C: 0, D: 1
/ \ \
E F G all leaves: 0
Degree of the tree: 3.
Sum of degrees: 3 + 2 + 1 = 6 = n − 1 for 7 nodes.
Leaves predicted by the formula: 1 + (2 + 1 + 0) = 4, matching C, E, F, G.
Complexity
Building the degree map touches each parent entry and each child once: O(n) time and O(n) space for the maps (the input adjacency is not counted). No recursion is used.
Edge Cases
Empty tree: no nodes, tree degree 0 by convention (default=0).
Single node: degree 0, which is both the node and tree degree.
Degenerate (path-like) tree: every internal node has degree 1, giving the maximum height n − 1.
Unrooted input: if degrees are computed from an undirected adjacency list, leaves have degree 1, not 0.
Interview Tips
Mention the two definitions and the sums n − 1 (rooted) and 2(n − 1) (unrooted); both follow from counting edges.
Connect degree to height and I/O: that is why databases use high-degree B-trees and in-memory maps use binary trees.
A common follow-up: “given the degree sequence, how many leaves are there?” Use L = 1 + Σ (d − 1) over internal nodes.
A frequent mistake is counting the parent in a rooted-tree degree.
10
Explain the concept of a Path in a tree.
KnownRevise
A path in a tree is a sequence of nodes in which each consecutive pair is joined by an edge and no node repeats. Its length is the number of edges (one less than the number of nodes). Because a tree has no cycles, there is exactly one path between any two nodes, and in a rooted tree it always climbs from the first node up to their lowest common ancestor (LCA) and then goes down to the second node.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Kinds of Paths
Path
Description
Example use
Root-to-node
From the root down to one node; length = depth
Finding a file by its full path
Root-to-leaf
Ends at a leaf
“Path sum” problems, decision rules in a decision tree
Downward path
From a node to any descendant
Counting paths with a given sum
General path
Between any two nodes, through their LCA
Distance between nodes, diameter, maximum path sum
The height of a node is the length of the longest downward path from it to a leaf.
Example
1
/ \
2 3
/ \ \
4 5 6
/
7
Path from 7 to 6: 7 → 4 → 2 → 1 → 3 → 6, length 5, through LCA 1.
Path from 7 to 5: 7 → 4 → 2 → 5, length 3, through LCA 2.
Code Example
The function records each node’s parent with an iterative DFS, climbs from both nodes to the LCA, and joins the two halves.
from __future__ import annotations
from dataclasses import dataclass
@dataclass(eq=False)
class TreeNode:
value: int
left: TreeNode | None = None
right: TreeNode | None = None
def path_between(root: TreeNode | None, start: TreeNode, end: TreeNode) -> list[int]:
"""Return the values on the unique path from start to end."""
parent: dict[TreeNode, TreeNode | None] = {}
if root is not None:
parent[root] = None
stack = [root] if root else []
while stack:
node = stack.pop()
for child in (node.left, node.right):
if child:
parent[child] = node
stack.append(child)
if start not in parent or end not in parent:
raise ValueError("both nodes must be in the tree")
ancestors_of_start: list[TreeNode] = []
node: TreeNode | None = start
while node is not None:
ancestors_of_start.append(node)
node = parent[node]
on_start_side = set(ancestors_of_start)
down_part: list[TreeNode] = []
node = end
while node not in on_start_side:
down_part.append(node)
node = parent[node]
lca = node
up_part = ancestors_of_start[:ancestors_of_start.index(lca) + 1]
return [n.value for n in up_part] + [n.value for n in reversed(down_part)]
n7 = TreeNode(7)
n4 = TreeNode(4, n7)
n5 = TreeNode(5)
n6 = TreeNode(6)
root = TreeNode(1, TreeNode(2, n4, n5), TreeNode(3, None, n6))
print(path_between(root, n7, n6)) # [7, 4, 2, 1, 3, 6]
print(path_between(root, n7, n5)) # [7, 4, 2, 5]
print(path_between(root, n4, n4)) # [4]
eq=False makes nodes hashable by identity, so duplicate values do not collide in the dictionaries.
Walkthrough for 7 → 6
Ancestors of 7: [7, 4, 2, 1].
Climb from 6: 6 and 3 are not ancestors of 7; 1 is, so the LCA is 1 and the downward part is [6, 3].
Up part [7, 4, 2, 1] plus reversed down part [3, 6] gives the path.
Complexity
Time: O(n) to build the parent map, plus O(h) to climb; total O(n) per query. With many queries, store the parent map once and use binary lifting for O(log n) LCA queries after O(n log n) preprocessing.
Space: O(n) for the parent map and ancestor set; the stack is O(h) for typical shapes. No recursion.
Edge Cases
Same node: the path is just [node], length 0.
One node is an ancestor of the other: the LCA is that node; the up or down part is short.
Node not in the tree: raises ValueError.
Duplicate values: handled because nodes are tracked by identity, not value.
Skewed tree: height n − 1, still fine because the code is iterative.
Interview Tips
Say “exactly one path, and it goes through the LCA”; most tree path problems build on that.
Know the distance formula with depths and the LCA.
Common follow-ups: root-to-leaf path sum, all paths with a given sum, diameter, and maximum path sum.
A frequent mistake is counting nodes instead of edges for path length; state which one the problem wants.
11
What is a Binary Search Tree (BST)?
KnownRevise
A binary search tree (BST) is a binary tree that keeps keys in order: for every node, all keys in its left subtree are smaller and all keys in its right subtree are larger. This invariant lets search, insert and delete discard one subtree at each step, so they cost O(h), where h is the height: O(log n) when the tree is balanced, but O(n) when it degenerates into a chain. An inorder traversal visits the keys in sorted order.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Invariant
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
Every key in 8‘s left subtree (1, 3, 4, 6, 7) is smaller than 8, and every key on the right (10, 13, 14) is larger. The rule applies to whole subtrees, not just direct children: 7 must be less than 8 even though it is a grandchild.
Operations
Operation
How
Time
Search
Compare with the node; go left if smaller, right if larger
O(h)
Insert
Search for the key; attach a new leaf where the search ends
O(h)
Delete
Leaf: remove. One child: splice it in. Two children: replace with the inorder successor (smallest key in the right subtree), then delete that node
O(h)
Min / max
Follow left / right pointers to the end
O(h)
Inorder traversal
Left, node, right
O(n), sorted output
Successor, floor, ceiling, range query
Walk down using comparisons
O(h), plus O(k) to report k results
h is ⌊log₂ n⌋ at best and n − 1 at worst. Inserting already sorted keys into a plain BST produces the worst case. Self-balancing trees (AVL, red-black) keep h = O(log n) by rotating after updates.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
class BST:
"""Binary search tree without duplicates; iterative operations."""
def __init__(self) -> None:
self.root: Node | None = None
def insert(self, key: int) -> bool:
"""Insert key; return False if it was already present."""
if self.root is None:
self.root = Node(key)
return True
current = self.root
while True:
if key == current.key:
return False
branch = "left" if key < current.key else "right"
child = getattr(current, branch)
if child is None:
setattr(current, branch, Node(key))
return True
current = child
def contains(self, key: int) -> bool:
current = self.root
while current and current.key != key:
current = current.left if key < current.key else current.right
return current is not None
def inorder(self) -> list[int]:
result: list[int] = []
stack: list[Node] = []
current = self.root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
result.append(current.key)
current = current.right
return result
tree = BST()
for key in [8, 3, 10, 1, 6, 14, 4, 7, 13]:
tree.insert(key)
print(tree.inorder()) # [1, 3, 4, 6, 7, 8, 10, 13, 14]
print(tree.contains(7), tree.contains(5)) # True False
print(tree.insert(6)) # False
Walkthrough: contains(7)
Step
Node
Comparison
Move
1
8
7 < 8
left
2
3
7 > 3
right
3
6
7 > 6
right
4
7
equal
found
Four comparisons instead of scanning nine keys.
Complexity
Time: O(h) for search and insert; O(n) for inorder. Best case O(1) when the key is at the root.
Space: O(n) for the tree; O(1) extra for iterative search and insert; O(h) for the inorder stack. A recursive version uses O(h) call stack, which can reach n on a skewed tree.
Edge Cases
Empty tree: search returns False; the first insert creates the root.
Duplicates: this version rejects them; alternatives are a count per node or a consistent “equal goes right” rule.
Negative numbers: compared normally.
Already sorted input: creates a chain of height n − 1; shuffle the input or use a balanced tree.
Interview Tips
State the invariant for subtrees, not just children; checking only children is the classic bug in “validate BST”.
Mention that a plain BST is O(n) in the worst case and name AVL or red-black trees as the fix.
Common follow-ups: delete with two children (inorder successor), kth smallest via inorder, LCA in a BST, and converting a sorted array into a balanced BST.
In Python, the standard library has no built-in BST; bisect on a sorted list or a third-party sorted container is often used instead.
12
Explain the difference between a Binary Tree and a Binary Search Tree (BST).
KnownRevise
A binary tree is only a shape rule: every node has at most two children. A binary search tree adds an ordering rule: for every node, all keys in the left subtree are smaller and all keys in the right subtree are larger. Every BST is a binary tree, but most binary trees are not BSTs. The ordering is what lets a BST search in O(h) instead of examining every node.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Binary tree
Binary search tree
Rule
At most 2 children
At most 2 children and left < node < right for whole subtrees
Search for a value
O(n): may need to visit every node
O(h): one root-to-leaf path
Insert
Anywhere the shape allows (often level order)
Exactly one correct position, found by comparisons
Delete
Replace with any node (often the deepest)
Must preserve order: leaf, one child, or two children with the inorder successor
Inorder traversal
Arbitrary order
Sorted order
Min / max
O(n)
O(h): leftmost / rightmost node
Duplicates
No issue
Needs a policy (reject, count, or always go right)
Typical uses
Expression trees, Huffman trees, heaps (with heap order), parse trees
Ordered maps and sets, range queries, symbol tables
Same Values, Two Trees
Binary tree, not a BST: BST with the same keys:
5 5
/ \ / \
9 2 2 9
Both have the same shape and keys. The left one breaks the ordering rule because 9 sits in 5’s left subtree.
Code Example
The same search on both kinds of tree shows the difference in work done.
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def search_binary_tree(root: Node | None, target: int) -> tuple[bool, int]:
"""Level-order search of any binary tree; returns (found, nodes visited)."""
visited = 0
queue: deque[Node] = deque([root] if root else [])
while queue:
node = queue.popleft()
visited += 1
if node.key == target:
return True, visited
queue.extend(child for child in (node.left, node.right) if child)
return False, visited
def search_bst(root: Node | None, target: int) -> tuple[bool, int]:
"""BST search that discards one subtree per step; returns (found, nodes visited)."""
visited = 0
node = root
while node:
visited += 1
if target == node.key:
return True, visited
node = node.left if target < node.key else node.right
return False, visited
bst = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))), Node(10, None, Node(14, Node(13))))
print(search_binary_tree(bst, 13)) # (True, 9)
print(search_bst(bst, 13)) # (True, 4)
print(search_bst(bst, 5)) # (False, 4)
Both functions find 13, but the generic search visits all nine nodes while the BST search follows one path 8 → 10 → 14 → 13.
Complexity
Operation
Binary tree
BST (balanced)
BST (degenerate)
Search
O(n)
O(log n)
O(n)
Insert
O(1) to O(n) depending on where
O(log n)
O(n)
Delete
O(n) to find the node
O(log n)
O(n)
Space
O(n)
O(n)
O(n)
The searches above use O(w) extra space for the queue (widest level) and O(1) for the BST walk; neither recurses.
Choosing
Use a plain binary tree when the structure itself carries meaning (an expression, a decision, a hierarchy) and ordering is irrelevant.
Use a BST when you need ordered data with fast lookup, ordered iteration, or range queries, and make it self-balancing (AVL, red-black) if inputs can arrive sorted.
Use a hash table instead when you need only exact-match lookups and no ordering.
Edge Cases
Empty trees: both searches return (False, 0).
Duplicates break the strict < / > rule unless a policy is defined.
A binary tree whose children are ordered locally but not across subtrees is not a BST (for example, 7 in the left subtree of 5).
Interview Tips
One sentence wins: “A BST is a binary tree plus the ordering invariant over entire subtrees.”
A common follow-up is “validate a BST”; pass min and max bounds down the tree, or check that the inorder sequence is strictly increasing.
A frequent mistake is saying BST operations are always O(log n); they are O(h).
13
What is a Complete Binary Tree?
KnownRevise
A complete binary tree is a binary tree in which every level is completely filled except possibly the last, and the last level’s nodes are as far left as possible. That shape means the tree can be stored in an array with no gaps: the node at index i has children at 2i + 1 and 2i + 2. Binary heaps rely on exactly this property.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The middle tree has a gap at 3‘s left child; the right tree has a gap at 2’s right child before 5.
Properties
Property
Value for n nodes
Height (edges)
⌊log₂ n⌋, the minimum possible
Array layout
Node i: left 2i + 1, right 2i + 2, parent (i − 1) // 2
Leaves
⌈n / 2⌉, at indexes ⌊n/2⌋ … n − 1
Internal nodes
⌊n / 2⌋
Nodes with one child
At most one, and it has only a left child
A perfect tree is complete with a full last level. A complete tree need not be full: in the first example, 3 has only a left child.
Checking Completeness
Do a level-order traversal including empty children. Once an empty slot is seen, every later slot must also be empty.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def is_complete(root: Node | None) -> bool:
"""Level-order check: no node may appear after an empty slot."""
queue: deque[Node | None] = deque([root])
seen_gap = False
while queue:
node = queue.popleft()
if node is None:
seen_gap = True
continue
if seen_gap:
return False
queue.append(node.left)
queue.append(node.right)
return True
def count_nodes_complete(root: Node | None) -> int:
"""Count nodes of a complete tree in O(log^2 n) by finding perfect subtrees."""
count = 0
node = root
while node:
left_height = height_of(node.left)
right_height = height_of(node.right)
if left_height == right_height:
count += 1 << left_height # perfect left subtree (2^lh - 1 nodes) plus this node
node = node.right
else:
count += 1 << right_height # perfect right subtree plus this node
node = node.left
return count
def height_of(node: Node | None) -> int:
"""Number of nodes on the leftmost path (valid height for complete trees)."""
height = 0
while node:
height += 1
node = node.left
return height
complete = Node(1, Node(2, Node(4), Node(5)), Node(3, Node(6)))
gap = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(is_complete(complete), is_complete(gap)) # True False
print(count_nodes_complete(complete)) # 6
Walkthrough of is_complete(gap)
Dequeued
Action
seen_gap
1
enqueue 2, 3
False
2
enqueue 4, 5
False
3
enqueue None, 6
False
4, 5
enqueue their empty children
False
None (3’s left)
mark gap
True
6
node after a gap
return False
Complexity
is_complete: O(n) time, O(w) queue space (up to about n/2).
count_nodes_complete: each step measures heights in O(log n) and descends one level, so O(log² n) time and O(1) extra space, much faster than O(n) counting for large trees.
No recursion; the tree itself is not counted in the space figures.
Edge Cases
Empty tree: complete by convention; count 0.
Single node: complete; count 1.
Only a right child: not complete.
Values: irrelevant; completeness is about shape only.
Interview Tips
Connect the definition to the array layout and to heaps; that is the point interviewers want.
Know the O(log² n) node count; it is a classic follow-up.
A frequent mistake is the “every node has 0 or 2 children” check, which tests fullness, not completeness.
14
Define a Perfect Binary Tree and its characteristics.
KnownRevise
A perfect binary tree is a binary tree in which every internal node has exactly two children and every leaf is at the same depth. It is the most regular binary tree possible: with height h (in edges) it contains exactly 2^(h+1) − 1 nodes, of which 2^h are leaves. Every perfect tree is both full and complete.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Characteristics
Property
Value for height h
Nodes at depth d
2^d
Total nodes
2^(h+1) − 1
Leaves
2^h (just over half of all nodes)
Internal nodes
2^h − 1 (leaves = internal + 1)
Height from n nodes
log₂(n + 1) − 1
Possible sizes
Only 1, 3, 7, 15, 31, …
Array layout
Fills indexes 0 … n − 1 with no gaps
Example (height 2)
1
/ \
2 3
/ \ / \
4 5 6 7
7 nodes, 4 leaves, 3 internal nodes, all leaves at depth 2.
Relation to Other Types
Type
Perfect tree satisfies it?
Converse?
Full (0 or 2 children)
Yes
No: leaves can be at different depths
Complete (filled left to right)
Yes
No: last level may be partial
Balanced (heights differ by ≤ 1)
Yes, with difference 0 everywhere
No
Where Perfect Trees Appear
Segment trees over an array whose size is a power of two.
Tournament brackets with 2^h players.
Analysis: worst-case bounds often assume a perfect tree, because it maximises the node count for a height.
Binary heaps are perfect whenever n is one less than a power of two.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def is_perfect(root: Node | None) -> bool:
"""Level-order check: level d must hold exactly 2**d nodes, all leaves on the last level."""
if root is None:
return True
queue: deque[Node] = deque([root])
expected = 1
while queue:
if len(queue) != expected:
return False
has_children = [node.left is not None and node.right is not None for node in queue]
has_any_child = [node.left is not None or node.right is not None for node in queue]
if all(has_children):
for _ in range(len(queue)):
node = queue.popleft()
queue.append(node.left)
queue.append(node.right)
expected *= 2
elif not any(has_any_child):
return True # every node on this level is a leaf
else:
return False # mixed level: some leaves, some internal nodes
return True
def build_perfect(height: int) -> Node | None:
"""Build a perfect tree of the given height with level-order values 1, 2, 3, ..."""
if height < 0:
return None
nodes = [Node(i + 1) for i in range(2 ** (height + 1) - 1)]
for i, node in enumerate(nodes):
if 2 * i + 2 < len(nodes):
node.left, node.right = nodes[2 * i + 1], nodes[2 * i + 2]
return nodes[0]
tree = build_perfect(2)
print(is_perfect(tree)) # True
tree.right.right = None
print(is_perfect(tree)) # False
Walkthrough of is_perfect on the Height-2 Tree
Level
Nodes in queue
Expected
Children
0
[1]
1
all have two → next level
1
[2, 3]
2
all have two → next level
2
[4, 5, 6, 7]
4
none have children → perfect
After removing 7, level 1 is mixed (3 has one child), so the check fails.
Complexity
is_perfect visits each node once: O(n) time and O(w) queue space, where the last level holds (n + 1)/2 nodes. build_perfect creates n nodes in O(n) time and space. Neither recurses.
Size not of the form 2^k − 1: cannot be perfect; a quick pre-check if you know n.
Values: irrelevant; perfection is about shape.
Interview Tips
Give the formulas (2^(h+1) − 1 nodes, 2^h leaves) and the perfect ⊂ complete, perfect ⊂ full relationships.
A common follow-up: “populate next-right pointers in a perfect binary tree”, which uses the regular shape to link levels in O(1) extra space.
A frequent mistake is using “complete” and “perfect” interchangeably; textbooks differ in older terminology, so define your terms.
15
Explain what a Degenerate (or Pathological) Tree is and its impact on operations.
KnownRevise
A degenerate (or pathological) tree is one in which every internal node has exactly one child, so the tree is really a linked list: its height is n − 1, the maximum possible. In a binary search tree this destroys the benefit of the tree: search, insert and delete, which cost O(h), become O(n) instead of O(log n). The usual cause is inserting keys in sorted or nearly sorted order into a BST that does not rebalance.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
All three have height 4 for 5 nodes. A zig-zag shape (from inserting 1, 5, 2, 4, 3) is degenerate too, even though it is not one-sided.
Impact on Operations
Operation
Balanced BST
Degenerate BST
Search, insert, delete
O(log n)
O(n)
Min / max
O(log n)
O(1) or O(n), depending on direction
Build from n keys
O(n log n)
O(n²) (1 + 2 + … + n comparisons)
Recursive traversal stack depth
O(log n)
O(n): about 1,000 nodes is enough to hit Python’s default recursion limit
Memory
O(n) nodes
O(n) nodes, but no benefit over a list for the pointer overhead
For a million sorted keys, building a plain BST takes about half a trillion comparisons, while a balanced tree needs about 20 million.
Code Example
from __future__ import annotations
import random
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def insert(root: Node | None, key: int) -> Node:
"""Iterative BST insert that ignores duplicates; returns the root."""
new = Node(key)
if root is None:
return new
current = root
while True:
if key == current.key:
return root
if key < current.key:
if current.left is None:
current.left = new
return root
current = current.left
else:
if current.right is None:
current.right = new
return root
current = current.right
def height(root: Node | None) -> int:
"""Height in edges via an explicit stack; -1 for an empty tree."""
best = -1
stack = [(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
keys = list(range(1, 1001))
sorted_root = None
for key in keys:
sorted_root = insert(sorted_root, key)
shuffled = keys[:]
random.Random(42).shuffle(shuffled)
shuffled_root = None
for key in shuffled:
shuffled_root = insert(shuffled_root, key)
print(height(sorted_root)) # 999
print(height(shuffled_root)) # 20
Inserting 1,000 sorted keys gives height 999; the same keys shuffled give height 20, because a random insertion order gives an expected height of O(log n). The minimum possible height for 1,000 nodes is 9.
How to Avoid It
Approach
Guarantee
Cost
Self-balancing BST (AVL, red-black)
O(log n) worst case
Rotations and extra fields per node
B-tree family (for storage)
O(log n), very shallow
More complex nodes
Randomised structures (treap, skip list)
O(log n) expected
Randomness; worst case still possible
Shuffle keys before a one-off build
Expected O(log n) height
Only works when all keys are known up front
Build from a sorted array by picking the middle
Exactly balanced
Static; later inserts can unbalance it
Splay tree
O(log n) amortized
Individual operations can be O(n)
Edge Cases
A tree with 0, 1 or 2 nodes is trivially degenerate and balanced at the same time.
Duplicates with an “equal goes right” rule turn many copies of one key into a chain; count duplicates per node instead.
Nearly sorted data (timestamps, auto-increment IDs) is the common real-world trigger.
Interview Tips
Lead with “height becomes n − 1, so O(h) operations become O(n)”, and name sorted input as the cause.
Mention the recursion depth problem: recursive traversals of a degenerate tree overflow the stack in Python.
A common follow-up: “how do you build a balanced BST from a sorted array?” Pick the middle element as the root recursively, O(n) time.
A frequent mistake is quoting O(log n) for BST operations without stating that it requires balance.
16
Discuss the concept of a Balanced Binary Tree and why it’s important.
KnownRevise
A balanced binary tree keeps its height close to the minimum, O(log n). The most common definition (used by AVL trees and the classic interview problem) is height-balanced: for every node, the heights of the left and right subtrees differ by at most 1. Balance matters because search, insert and delete in a BST cost O(h); a balanced tree guarantees O(log n), while an unbalanced one can degrade to O(n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Definitions of “Balanced”
Definition
Rule
Height guarantee
Used by
Height-balanced
‘
height(left) − height(right)
≤ 1` at every node
≤ about 1.44 · log₂ n
AVL trees, interview problem
Red-black rules
No red node has a red child; equal black count on every root-to-leaf path
≤ 2 · log₂(n + 1)
Red-black trees
Weight-balanced
Subtree sizes within a constant ratio
O(log n)
Some functional-language sets
Perfectly balanced
All leaves at depth h or h − 1
⌊log₂ n⌋
Trees built from sorted arrays
The rule must hold at every node. A tree whose root has equal-height subtrees can still be unbalanced deeper down.
Why It Is Important
Concern
Balanced (h ≈ log n)
Unbalanced (h up to n − 1)
Lookup in 1 million keys
About 20 levels
Up to 1 million
Insert and delete
O(log n)
O(n)
Recursion depth
~20 frames
Can exceed Python’s ~1,000 limit
Predictable latency
Yes
Depends on input order
Real systems need worst-case guarantees: a map whose speed depends on whether keys arrived sorted is a performance bug waiting to happen, and adversarial input can trigger it deliberately.
Checking Balance in One Pass
The naive check computes heights separately at every node, which is O(n²) on a skewed tree. The efficient version computes each subtree’s height once, bottom-up, and reports imbalance immediately. This iterative postorder version avoids recursion limits.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
value: int
left: Node | None = None
right: Node | None = None
def is_height_balanced(root: Node | None) -> bool:
"""Return True if every node's subtree heights differ by at most 1 (iterative postorder)."""
heights: dict[Node | None, int] = {None: -1}
stack: list[tuple[Node, bool]] = [(root, False)] if root else []
while stack:
node, children_done = stack.pop()
if children_done:
left_height, right_height = heights[node.left], heights[node.right]
if abs(left_height - right_height) > 1:
return False
heights[node] = 1 + max(left_height, right_height)
else:
stack.append((node, True))
for child in (node.right, node.left):
if child:
stack.append((child, False))
return True
balanced = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
unbalanced = Node(1, Node(2, Node(3, Node(4))), Node(5))
print(is_height_balanced(balanced)) # True
print(is_height_balanced(unbalanced)) # False
Walkthrough on unbalanced
1
/ \
2 5
/
3
/
4
Node finished
Left height
Right height
Difference
Result
4
−1
−1
0
height 0
3
0
−1
1
height 1
2
1
−1
2
unbalanced → False
The check stops at node 2 and never needs to reach the root.
Complexity
Each node is pushed twice and its height computed once: O(n) time. The height map is O(n) space and the stack O(h); the tree itself is not counted. The recursive equivalent is also O(n) time but uses O(h) call-stack space, up to n on skewed input.
Keeping Trees Balanced
AVL trees store heights and rotate after each insert or delete when a node’s balance factor reaches ±2.
Red-black trees recolour and rotate to restore their rules, doing fewer rotations than AVL on updates.
B-trees split and merge nodes so all leaves stay at the same depth.
Static data: build from sorted input by choosing middle elements as roots.
Edge Cases
Empty tree and single node: balanced.
A perfect tree: balanced with difference 0 everywhere.
A complete tree: always height-balanced.
A tree can be balanced without being complete (gaps in the last level on both sides).
Interview Tips
Give the precise rule (difference ≤ 1 at every node) and the reason (O(h) operations).
Show the O(n) single-pass check, not the O(n²) version, and mention the recursion-depth issue in Python.
Common follow-ups: “how does an AVL tree restore balance?” (four rotation cases) and “AVL versus red-black” (stricter balance and faster lookups versus fewer rotations on updates).
17
What is a Balanced Tree?
KnownRevise
A balanced tree is a tree whose height stays O(log n) for n nodes, no matter in which order keys are inserted or deleted. Balance is not one rule but a family of invariants (subtree heights, node colours, subtree sizes, or equal leaf depth) that each guarantee logarithmic height, so that searches, inserts and deletes all run in O(log n). Self-balancing trees restore their invariant after every update with rotations, recolouring or node splits and merges.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Why Balance Is Needed
A tree’s operations follow root-to-leaf paths, so their cost is proportional to the height. Without a balance rule, inserting sorted keys into a BST creates a chain of height n − 1, and every operation becomes O(n).
n keys
Height when balanced (about log₂ n)
Height when degenerate
1,000
~10
999
1,000,000
~20
999,999
Balanced Tree Families
Tree
Balance invariant
Height bound
Restoring balance
Typical use
AVL
Subtree heights differ by ≤ 1 at every node
≈ 1.44 log₂ n
Single and double rotations
Read-heavy in-memory indexes
Red-black
Colour rules: no red parent of red child; equal black height
≤ 2 log₂(n + 1)
Recolouring plus at most 2 rotations per insert, 3 per delete
Standard library maps (C++ std::map, Java TreeMap)
B-tree / B+ tree
Every node between ⌈m/2⌉ and m children; all leaves at the same depth
≈ log_{m/2} n
Split full nodes, merge or borrow on underflow
Databases, file systems
2-3 tree
Nodes have 2 or 3 children; all leaves at the same depth
≤ log₂ n
Splits and merges
Teaching; equivalent to left-leaning red-black trees
Weight-balanced
Subtree sizes within a fixed ratio
O(log n)
Rotations
Functional sets and maps
Treap
Heap order on random priorities
O(log n) expected
Rotations
Simple randomised balancing
Splay
None stored; recently used keys moved to the root
O(log n) amortized
Splaying (rotations on access)
Caches with locality
Scapegoat
Size-based; rebuild a subtree when too deep
O(log n) amortized updates
Rebuild subtrees
No per-node balance data
Two kinds of guarantee appear: worst-case (AVL, red-black, B-tree) and expected or amortized (treap, splay, scapegoat). Systems that need predictable latency for every operation prefer worst-case structures.
What a Rotation Does
A rotation changes the shape locally while keeping the BST order:
Right rotation at y:
y x
/ \ / \
x C → A y
/ \ / \
A B B C
Order is still A < x < B < y < C. Only three pointers change, so a rotation is O(1).
Small Demonstration
import math
def min_height(node_count: int) -> int:
"""Smallest possible binary tree height (in edges) for node_count nodes."""
return math.floor(math.log2(node_count)) if node_count > 0 else -1
def max_avl_height(node_count: int) -> int:
"""Largest AVL height for node_count nodes, using the minimum-size recurrence N(h) = N(h-1) + N(h-2) + 1."""
sizes = [1, 2] # minimum nodes for heights 0 and 1
while sizes[-1] <= node_count:
sizes.append(sizes[-1] + sizes[-2] + 1)
return len(sizes) - 2
for count in (10, 1_000, 1_000_000):
print(count, min_height(count), max_avl_height(count), count - 1)
# 10 3 3 9
# 1000 9 13 999
# 1000000 19 27 999999
Even the most lopsided legal AVL tree with a million nodes has height 27, compared with 999,999 for a degenerate BST.
Complexity
Operation
Balanced tree
Unbalanced BST worst case
Search
O(log n)
O(n)
Insert / delete
O(log n), including rebalancing
O(n)
Ordered traversal
O(n)
O(n)
Space
O(n), plus a small balance field per node (height, colour, priority)
O(n)
The demonstration runs in O(log n) time and space for the recurrence list.
Choosing
In-memory ordered map: use the language’s library (TreeMap, std::map); in Python, a sorted list with bisect or the sortedcontainers package.
Many lookups, few updates: AVL.
Mixed updates: red-black.
Data on disk or SSD: B+ tree.
Want simple code with good expected behaviour: treap or skip list.
Interview Tips
Define balance by its purpose (height O(log n)) and then name the invariant of the tree you discuss.
Distinguish worst-case, expected and amortized guarantees.
A common follow-up is drawing a rotation and explaining why it preserves order.
A frequent mistake is saying a balanced tree must be complete or perfect; balanced trees can have uneven leaf depths.
18
Classify Tree Traversal Algorithms.
KnownRevise
Tree traversals fall into two main families. Depth-first traversals go as deep as possible along one branch before backtracking; for binary trees they are preorder (node, left, right), inorder (left, node, right) and postorder (left, right, node), named by when the node is visited relative to its children. Breadth-first traversal (level order) visits nodes level by level using a queue. Variants such as zigzag, reverse orders and Morris traversal build on these.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Classification
Family
Traversal
Order
Data structure
Typical use
Depth-first
Preorder
Node, left, right
Stack or recursion
Copying or serialising a tree, prefix expressions
Depth-first
Inorder
Left, node, right
Stack or recursion
Sorted output of a BST, infix expressions
Depth-first
Postorder
Left, right, node
Stack or recursion
Deleting a tree, computing subtree results (heights, sizes), postfix expressions
Depth-first
Reverse inorder
Right, node, left
Stack or recursion
BST in descending order, kth largest
Breadth-first
Level order
Level by level, left to right
Queue
Shortest path in edges, printing by level, nearest leaf
Breadth-first
Zigzag (spiral)
Alternate direction each level
Queue or two stacks
Spiral printing problems
Constant space
Morris traversal
Inorder or preorder
Temporary threads in the tree
O(1) extra space
Specialised
Vertical, boundary, diagonal, Euler tour
Problem-specific
Map plus queue, or stacks
Views of a tree, LCA via Euler tour
For n-ary trees, preorder, postorder and level order generalise directly; inorder does not, because there is no single “middle” child.
Example
1
/ \
2 3
/ \ \
4 5 6
Traversal
Result
Preorder
1, 2, 4, 5, 3, 6
Inorder
4, 2, 5, 1, 3, 6
Postorder
4, 5, 2, 6, 3, 1
Level order
1, 2, 3, 4, 5, 6
Zigzag
1, 3, 2, 4, 5, 6
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def preorder(root: Node | None) -> list[int]:
result, stack = [], [root] if root else []
while stack:
node = stack.pop()
result.append(node.value)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
def inorder(root: Node | None) -> list[int]:
result, stack, node = [], [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.value)
node = node.right
return result
def postorder(root: Node | None) -> list[int]:
"""Reverse of a node-right-left preorder."""
result, stack = [], [root] if root else []
while stack:
node = stack.pop()
result.append(node.value)
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return result[::-1]
def level_order(root: Node | None) -> list[list[int]]:
levels, queue = [], deque([root] if root else [])
while queue:
levels.append([])
for _ in range(len(queue)):
node = queue.popleft()
levels[-1].append(node.value)
queue.extend(child for child in (node.left, node.right) if child)
return levels
tree = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(preorder(tree)) # [1, 2, 4, 5, 3, 6]
print(inorder(tree)) # [4, 2, 5, 1, 3, 6]
print(postorder(tree)) # [4, 5, 2, 6, 3, 1]
print(level_order(tree)) # [[1], [2, 3], [4, 5, 6]]
Complexity
Traversal
Time
Extra space
Pre-, in-, postorder (stack or recursion)
O(n)
O(h): about log n balanced, up to n skewed
Level order
O(n)
O(w): widest level, up to about n/2
Morris
O(n)
O(1), but temporarily modifies pointers
Every traversal must visit all n nodes, so best, average and worst time are all O(n). Output lists add O(n) space. The iterative versions avoid Python’s recursion limit on deep trees.
Choosing a Traversal
Need parents before children (copy, serialise, path from root): preorder.
Need sorted order from a BST: inorder.
Need children’s results before the parent (height, size, delete, evaluate): postorder.
Need nodes by distance from the root: level order.
Memory-constrained and the tree may be modified temporarily: Morris.
Interview Tips
Name the two families (DFS and BFS) and the three DFS orders by when the node is visited.
Be able to write each iteratively; interviewers often forbid recursion.
A common follow-up: reconstruct a tree from preorder and inorder sequences.
A frequent mistake is writing iterative preorder that pushes the left child first, which visits the right subtree before the left.
19
How to perform an In-Order Traversal in a Binary Search Tree (BST)?
KnownRevise
An in-order traversal visits the left subtree, then the node, then the right subtree. In a binary search tree this visits the keys in ascending sorted order, because every key in the left subtree is smaller than the node and every key in the right subtree is larger. It can be written recursively, iteratively with an explicit stack, or with Morris traversal in O(1) extra space.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Algorithm (Iterative)
Start at the root with an empty stack.
While the current node exists, push it and move to its left child.
When there is no left child, pop a node, visit it, and move to its right child.
Repeat until both the stack is empty and the current node is None.
The stack holds the path of ancestors whose left subtrees are still being processed.
Code Example
from __future__ import annotations
from collections.abc import Iterator
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def inorder_recursive(root: Node | None) -> list[int]:
"""Simple recursive version; recursion depth equals tree height."""
if root is None:
return []
return inorder_recursive(root.left) + [root.key] + inorder_recursive(root.right)
def inorder_iter(root: Node | None) -> Iterator[int]:
"""Lazy iterative in-order traversal using an explicit stack."""
stack: list[Node] = []
current = root
while stack or current:
while current:
stack.append(current)
current = current.left
current = stack.pop()
yield current.key
current = current.right
def kth_smallest(root: Node | None, k: int) -> int:
"""Stop after k keys instead of traversing the whole tree."""
for index, key in enumerate(inorder_iter(root), start=1):
if index == k:
return key
raise ValueError("k is larger than the number of keys")
bst = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))), Node(10, None, Node(14, Node(13))))
print(list(inorder_iter(bst))) # [1, 3, 4, 6, 7, 8, 10, 13, 14]
print(inorder_recursive(bst) == list(inorder_iter(bst))) # True
print(kth_smallest(bst, 3)) # 4
The generator version uses the traversal lazily: kth_smallest stops after k keys. The recursive version is shorter, but list concatenation makes it O(n·h) in time; append to one shared list instead if you write it recursively in real code.
Walkthrough
8
/ \
3 10
/ \ \
1 6 14
/ \ /
4 7 13
Step
Action
Stack (bottom → top)
Output so far
1
Push 8, 3, 1 going left
8, 3, 1
2
Pop 1, visit; go right (none)
8, 3
1
3
Pop 3, visit; go right to 6; push 6, 4
8, 6, 4
1, 3
4
Pop 4, visit
8, 6
1, 3, 4
5
Pop 6, visit; go right, push 7
8, 7
1, 3, 4, 6
6
Pop 7, then 8; go right, push 10
10
…, 7, 8
7
Pop 10; go right, push 14, 13
14, 13
…, 10
8
Pop 13, then 14
empty
…, 13, 14
Complexity
Version
Time
Extra space
Iterative stack
O(n) for all keys; O(h + k) for the first k
O(h) stack
Recursive
O(n) with a shared list
O(h) call stack; can overflow at ~1,000 levels in Python
Morris
O(n)
O(1); temporarily rewires right pointers
h is O(log n) for a balanced BST and up to n − 1 for a degenerate one. Output space O(n) is extra if you collect a list.
Uses
Sorted output of a BST without a separate sort.
Validate a BST: the in-order sequence must be strictly increasing.
kth smallest element, and successor/predecessor of a key.
Range queries: traverse in order and stop once keys exceed the upper bound.
Convert a BST to a sorted list or doubly linked list.
Skewed tree: the stack grows to n for a left-skewed tree; the iterative code still works.
Duplicates: if your BST stores equal keys on one side, they appear adjacent in the output.
k ≤ 0 or larger than n: validate and raise.
Interview Tips
Say “in-order on a BST is sorted order” and write the iterative version from memory; it is asked constantly.
Mention Morris traversal as the O(1)-space follow-up.
Common follow-ups: kth smallest, validate BST, BST iterator with next() and has_next() in O(h) space.
A frequent mistake is forgetting to move to the right child after visiting, which loops forever on the same node.
20
Implement a Pre-Order Traversal in a binary tree.
KnownRevise
A pre-order traversal visits each node first, then its left subtree, then its right subtree (node, left, right). Because a parent is always visited before its children, pre-order is the natural traversal for copying or serialising a tree and for producing prefix (Polish) notation from an expression tree. Iteratively, use a stack and push the right child before the left, so the left subtree is processed first.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Algorithm (Iterative)
If the tree is empty, return an empty list.
Push the root onto a stack.
While the stack is not empty: pop a node, visit it, push its right child, then its left child (if present).
Because a stack is last-in, first-out, the left child is popped next.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
value: str
left: Node | None = None
right: Node | None = None
def preorder_recursive(root: Node | None, result: list[str] | None = None) -> list[str]:
"""Recursive pre-order; depth of recursion equals the tree height."""
if result is None:
result = []
if root is not None:
result.append(root.value)
preorder_recursive(root.left, result)
preorder_recursive(root.right, result)
return result
def preorder_iterative(root: Node | None) -> list[str]:
"""Iterative pre-order with an explicit stack: push right, then left."""
result: list[str] = []
stack = [root] if root else []
while stack:
node = stack.pop()
result.append(node.value)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
# Expression tree for (3 + 4) * (5 - 2)
expression = Node("*", Node("+", Node("3"), Node("4")), Node("-", Node("5"), Node("2")))
print(preorder_iterative(expression)) # ['*', '+', '3', '4', '-', '5', '2']
print(preorder_recursive(expression) == preorder_iterative(expression)) # True
print(preorder_iterative(None)) # []
The output * + 3 4 - 5 2 is the prefix notation of (3 + 4) * (5 − 2).
Walkthrough
*
/ \
+ -
/ \ / \
3 4 5 2
Step
Pop
Visit
Push (right, then left)
Stack after (top last)
1
*
*
-, +
-, +
2
+
+
4, 3
-, 4, 3
3
3
3
none
-, 4
4
4
4
none
-
5
-
-
2, 5
2, 5
6
5
5
none
2
7
2
2
none
empty
Complexity
Time: O(n). Every node is pushed and popped exactly once; best, average and worst case are the same.
Space: O(h) for the stack or recursion in typical trees, where h is the height; the iterative stack can hold up to about h + 1 pending right children. In a degenerate tree h = n − 1. The result list adds O(n). The input tree is not counted.
The recursive version needs a raised recursion limit or an explicit stack once the tree is deeper than about 1,000 levels in Python.
Uses
Use
Why pre-order
Clone a tree
Create the parent before attaching children
Serialise (with null markers)
The root comes first, so deserialisation can rebuild top-down
Prefix expressions
Operator before operands
Print a directory tree
Folder name before its contents
Root-to-leaf path problems
The path is built on the way down
Edge Cases
Empty tree: returns [].
Single node: returns [root].
Only left or only right children: the stack never holds more than one pending node in a left-skewed tree.
Duplicates and negative values: visited like any other value; traversal does not compare values.
Common Pitfalls
Pushing the left child before the right, which visits the right subtree first.
Using a mutable default argument (result=[]) in the recursive version, which leaks results between calls; the code uses None instead.
Forgetting null markers when serialising: pre-order alone cannot rebuild a binary tree uniquely; you need null markers, or a second traversal (in-order).
Interviewers often follow up with Morris pre-order (O(1) space) or with iterative in-order and post-order using the same stack idea.
21
Implement a Post-Order Traversal in a binary tree.
KnownRevise
A post-order traversal visits the left subtree, then the right subtree, then the node (left, right, node). Each node is visited only after all of its descendants, which makes it the traversal for computing results from children upward: subtree heights and sizes, evaluating expression trees, and deleting or freeing a tree safely. Iteratively, use a stack and track the last visited node to know when a node’s right subtree is finished.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Approaches
Approach
Idea
Extra space
Recursive
Recurse left, recurse right, then visit
O(h) call stack
Two stacks / reversed pre-order
Produce node, right, left order and reverse it
O(n) for the reversed output
One stack with last_visited
Visit a node only when its right child is absent or already visited
O(h)
Morris post-order
Threading plus reversing paths
O(1), complex
Algorithm (One Stack)
Go left as far as possible, pushing nodes.
Look at the top node without popping it.
If it has a right child that has not been visited, move to that right child and repeat step 1.
Otherwise pop it, visit it, and record it as last_visited.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
value: str
left: Node | None = None
right: Node | None = None
def postorder_iterative(root: Node | None) -> list[str]:
"""Iterative post-order with one stack and a last-visited pointer."""
result: list[str] = []
stack: list[Node] = []
current = root
last_visited: Node | None = None
while stack or current:
while current:
stack.append(current)
current = current.left
top = stack[-1]
if top.right is not None and top.right is not last_visited:
current = top.right
else:
result.append(top.value)
last_visited = stack.pop()
return result
def evaluate(root: Node) -> float:
"""Evaluate an expression tree bottom-up, in post-order, without recursion."""
values: dict[Node, float] = {}
operations = {"+": lambda a, b: a + b, "-": lambda a, b: a - b,
"*": lambda a, b: a * b, "/": lambda a, b: a / b}
stack: list[tuple[Node, bool]] = [(root, False)]
while stack:
node, children_done = stack.pop()
if node.left is None and node.right is None:
values[node] = float(node.value)
elif children_done:
values[node] = operations[node.value](values[node.left], values[node.right])
else:
stack.append((node, True))
stack.append((node.right, False))
stack.append((node.left, False))
return values[root]
# (3 + 4) * (5 - 2)
expression = Node("*", Node("+", Node("3"), Node("4")), Node("-", Node("5"), Node("2")))
print(postorder_iterative(expression)) # ['3', '4', '+', '5', '2', '-', '*']
print(evaluate(expression)) # 21.0
The post-order sequence 3 4 + 5 2 - * is the postfix (reverse Polish) form, which a stack-based calculator evaluates left to right.
Walkthrough of postorder_iterative
Step
Action
Stack (bottom → top)
Output
1
Push *, +, 3 going left
*, +, 3
2
3 has no right: visit
*, +
3
3
+ has unvisited right 4: push 4
*, +, 4
3
4
Visit 4, then + (its right was just visited)
*
3, 4, +
5
* has unvisited right -: push -, 5
*, -, 5
6
Visit 5; push 2; visit 2
*, -
…, 5, 2
7
Visit -, then *
empty
…, -, *
Complexity
Time: O(n). Each node is pushed and popped once; the top-of-stack check is O(1). Best, average and worst case are equal.
Space: O(h) for the stack, where h is the height (up to n − 1 for a skewed tree), plus O(n) for the output. evaluate uses O(n) for the value map. No recursion, so deep trees are safe in Python.
Uses
Use
Why post-order
Delete or free a tree
Children are removed before their parent
Heights, sizes, subtree sums
A parent’s value depends on its children
Evaluate expressions
Operands before operators
Check balance, diameter, maximum path sum
Combine left and right results at the parent
Dependency order (build systems)
Dependencies before the things that need them
Edge Cases
Empty tree: returns [] (evaluate expects a non-empty tree).
Single node: returns [root].
Right-skewed tree: relies on the last_visited check to avoid revisiting the right child.
Duplicate values: the code compares nodes by identity (is), so equal values cannot confuse it; eq=False keeps nodes hashable by identity.
Division by zero in evaluate raises ZeroDivisionError; validate input if needed.
Common Pitfalls
Popping a node before its right subtree is done; the last_visited check prevents it.
Comparing nodes by value instead of identity, which breaks with duplicate values.
Using the “reverse a node-right-left pre-order” trick and forgetting it needs O(n) extra space and cannot stream results.
Interviewers often ask for the iterative version specifically, or use post-order as the basis for height, diameter and “lowest common ancestor” problems.
22
Discuss the applications of each type of Tree Traversal algorithm.
KnownRevise
Each traversal visits the same nodes but in a different order, and the order decides what it is good for. Pre-order (node first) suits work that must happen top-down: copying, serialising, prefix expressions. In-order gives sorted order in a BST. Post-order (node last) suits bottom-up work where a parent needs its children’s results: heights, sizes, deletion, evaluation. Level order (BFS) suits anything measured in distance from the root: shortest paths in edges, per-level views, nearest leaf.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Applications by Traversal
Traversal
Order
Applications
Pre-order
Node, left, right
Clone a tree; serialise with null markers; prefix (Polish) notation; print a directory tree; root-to-leaf path problems; build an Euler tour for LCA
In-order
Left, node, right
Sorted output of a BST; validate a BST; kth smallest; BST iterator; convert a BST to a sorted list; infix expressions
Reverse in-order
Right, node, left
Descending order; kth largest; “greater sum tree”
Post-order
Left, right, node
Delete or free a tree; compute height, size and subtree sums; check balance; diameter; maximum path sum; evaluate expression trees; postfix notation; dependency resolution
Level order (BFS)
Level by level
Minimum depth; right or left side view; level averages; zigzag printing; connecting next pointers; serialising heaps and complete trees; shortest path in unweighted trees and graphs
Morris
In-order or pre-order with temporary threads
Any of the above when O(1) extra space is required
Rule of Thumb
Do I need the parent’s information before the children? Pre-order.
Do I need the children’s answers before the parent? Post-order.
Is the tree a BST and do I need order? In-order.
Do I need the closest or shallowest something? Level order.
Code Example
One small function per family, each solving a typical problem.
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
value: int
left: Node | None = None
right: Node | None = None
def serialize_preorder(root: Node | None) -> str:
"""Pre-order with '#' for missing children: enough to rebuild the tree."""
parts: list[str] = []
stack: list[Node | None] = [root]
while stack:
node = stack.pop()
if node is None:
parts.append("#")
continue
parts.append(str(node.value))
stack.append(node.right)
stack.append(node.left)
return ",".join(parts)
def is_valid_bst(root: Node | None) -> bool:
"""In-order must be strictly increasing."""
previous = None
stack: list[Node] = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if previous is not None and node.value <= previous:
return False
previous = node.value
node = node.right
return True
def subtree_sizes(root: Node | None) -> dict[int, int]:
"""Post-order: a node's size is 1 plus its children's sizes."""
sizes: dict[Node | None, int] = {None: 0}
stack: list[tuple[Node, bool]] = [(root, False)] if root else []
while stack:
node, done = stack.pop()
if done:
sizes[node] = 1 + sizes[node.left] + sizes[node.right]
else:
stack += [(node, True)] + [(child, False) for child in (node.right, node.left) if child]
return {node.value: size for node, size in sizes.items() if node is not None}
def min_depth(root: Node | None) -> int:
"""Level order: the first leaf found is the shallowest."""
if root is None:
return 0
queue = deque([(root, 1)])
while queue:
node, depth = queue.popleft()
if node.left is None and node.right is None:
return depth
queue.extend((child, depth + 1) for child in (node.left, node.right) if child)
return 0
tree = Node(4, Node(2, Node(1), Node(3)), Node(6, None, Node(7)))
print(serialize_preorder(tree)) # 4,2,1,#,#,3,#,#,6,#,7,#,#
print(is_valid_bst(tree)) # True
print(subtree_sizes(tree)) # {1: 1, 3: 1, 2: 3, 7: 1, 6: 2, 4: 6}
print(min_depth(tree)) # 3
min_depth returns 3 here because the leaves 1 and 3 sit at depth 3 counting nodes (the convention LeetCode uses), and BFS finds 1 before visiting 7.
Complexity
All four functions are O(n) in the worst case; min_depth can stop early, so its best case is proportional to the nodes above the shallowest leaf. Extra space is O(h) for the stack-based ones and O(w) for BFS (widest level), plus O(n) for outputs and the size map. None recurse, so skewed trees are safe in Python.
Explain the choice in one sentence: top-down → pre-order, bottom-up → post-order, sorted → in-order, nearest → BFS.
Interviewers often ask why DFS is a poor choice for minimum depth: it must explore every path, while BFS stops at the first leaf.
A frequent mistake is serialising without null markers, which loses the tree’s shape.
23
Compare the iterative and recursive implementations of Tree Traversals.
KnownRevise
Both implementations visit the same nodes in the same order with O(n) time. Recursive traversals use the call stack to remember where to return, so they are short and mirror the definition, but each level costs a stack frame and Python stops at a recursion limit (about 1,000 by default). Iterative traversals manage an explicit stack or queue on the heap: more code, but no depth limit, easy early exit, and the ability to pause and resume (as an iterator).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Recursive
Iterative
Code size and clarity
Very short; matches the definition
Longer, especially post-order
Memory
O(h) call frames, each fairly large
O(h) stack entries (references only); O(w) queue for BFS
Depth limit
Python’s recursion limit (~1,000); deep trees raise RecursionError
Limited only by memory
Speed in Python
Function-call overhead per node
Usually somewhat faster; avoids call overhead
Early exit
Needs flags or exceptions to unwind
return or break directly
Pause/resume (iterators)
Needs generators with yield from, still recursive
Natural: keep the stack between next() calls
Level order (BFS)
Awkward
Natural with collections.deque
Bottom-up results (post-order)
Natural: return values from children
Needs a second visit marker or a result map
Error-proneness
Low
Higher: push order, last_visited bookkeeping
Some languages perform tail-call optimisation, but tree traversals are not tail-recursive (work remains after the first recursive call), and Python never does it anyway.
Code Example
The same in-order traversal both ways, run on a balanced tree and on a 5,000-node chain.
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def inorder_recursive(node: Node | None, out: list[int]) -> None:
"""Recursive in-order: left, node, right."""
if node is None:
return
inorder_recursive(node.left, out)
out.append(node.value)
inorder_recursive(node.right, out)
def inorder_iterative(root: Node | None) -> list[int]:
"""Same order with an explicit stack."""
out: list[int] = []
stack: list[Node] = []
node = root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
out.append(node.value)
node = node.right
return out
small = Node(2, Node(1), Node(3))
recursive_result: list[int] = []
inorder_recursive(small, recursive_result)
print(recursive_result, inorder_iterative(small)) # [1, 2, 3] [1, 2, 3]
chain = None
for value in range(5000, 0, -1):
chain = Node(value, left=chain) # left-skewed: depth 5,000
try:
inorder_recursive(chain, [])
print("recursive ok")
except RecursionError:
print("recursive: RecursionError") # printed
print(len(inorder_iterative(chain))) # 5000
The recursive version fails on the 5,000-deep chain; the iterative one handles it. sys.setrecursionlimit can raise the limit, but very deep recursion can still crash the interpreter when the C stack runs out, so iteration is the safe choice for untrusted or skewed input.
Converting Recursion to Iteration
Pre-order: stack; pop, visit, push right then left.
In-order: push the left spine, pop and visit, then move right.
Post-order: stack with (node, children_done) pairs, or a last_visited pointer.
Any recursion: push a frame object holding the node and “where to resume” state. This is exactly what the call stack does for you.
Complexity
Version
Time
Extra space
Recursive DFS
O(n)
O(h) call stack
Iterative DFS
O(n)
O(h) explicit stack
Iterative BFS
O(n)
O(w) queue
Morris
O(n)
O(1)
h ranges from about log₂ n (balanced) to n − 1 (skewed). Both versions also use O(n) for the output list.
When to Use Which
Balanced trees, small inputs, clarity first: recursive.
Possibly deep or skewed trees (sorted-insert BSTs, parsed nested data), production code in Python: iterative.
Lazy iteration (for key in tree): iterative stack inside an iterator class or generator.
Bottom-up computations where readability matters and depth is bounded: recursive post-order.
Interview Tips
Write the recursive version first if allowed, then explain how to convert it, and mention Python’s recursion limit.
Expect “now do it without recursion”, usually for in-order or post-order.
A common mistake is claiming the iterative version uses less memory in big-O terms; both are O(h). The real gains are no depth limit and lower per-frame overhead.
24
How can you traverse a binary tree Without Using Recursion or stack?
KnownRevise
Use Morris traversal. It visits a binary tree in in-order (or pre-order) using O(1) extra space by temporarily creating threads: for each node with a left subtree, it points the rightmost node of that left subtree (the node’s in-order predecessor) back to the node. That link replaces the stack’s job of remembering where to return. Each thread is removed on the second visit, so the tree is restored when the traversal ends. Other stack-free options are parent pointers or a permanently threaded tree.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Morris In-Order Algorithm
Set current = root.
While current is not None:
If current has no left child: visit it, then go to current.right.
Otherwise find predecessor, the rightmost node in current.left (stop if its right pointer already points to current).
If predecessor.right is None: create the thread predecessor.right = current, then go left.
If predecessor.right is current: the left subtree is done. Remove the thread, visit current, then go right.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass(eq=False)
class Node:
value: int
left: Node | None = None
right: Node | None = None
def morris_inorder(root: Node | None) -> list[int]:
"""In-order traversal in O(1) extra space; restores the tree before returning."""
result: list[int] = []
current = root
while current:
if current.left is None:
result.append(current.value)
current = current.right
continue
predecessor = current.left
while predecessor.right is not None and predecessor.right is not current:
predecessor = predecessor.right
if predecessor.right is None:
predecessor.right = current # create thread
current = current.left
else:
predecessor.right = None # remove thread
result.append(current.value)
current = current.right
return result
def morris_preorder(root: Node | None) -> list[int]:
"""Same idea, but visit a node when its thread is created."""
result: list[int] = []
current = root
while current:
if current.left is None:
result.append(current.value)
current = current.right
continue
predecessor = current.left
while predecessor.right is not None and predecessor.right is not current:
predecessor = predecessor.right
if predecessor.right is None:
result.append(current.value)
predecessor.right = current
current = current.left
else:
predecessor.right = None
current = current.right
return result
tree = Node(4, Node(2, Node(1), Node(3)), Node(6, Node(5), Node(7)))
print(morris_inorder(tree)) # [1, 2, 3, 4, 5, 6, 7]
print(morris_preorder(tree)) # [4, 2, 1, 3, 6, 5, 7]
print(tree.left.right.right) # None (threads were removed)
Walkthrough (In-Order)
4
/ \
2 6
/ \ / \
1 3 5 7
Step
current
Action
Output
1
4
Predecessor 3; thread 3 → 4; go left
2
2
Predecessor 1; thread 1 → 2; go left
3
1
No left: visit; follow thread to 2
1
4
2
Thread found at 1; remove; visit; go right
1, 2
5
3
No left: visit; follow thread to 4
1, 2, 3
6
4
Thread found at 3; remove; visit; go right
…, 4
7
6, 5, 6, 7
Same pattern on the right subtree
…, 5, 6, 7
Complexity
Time: O(n). Finding predecessors walks some edges more than once, but each edge is traversed at most a constant number of times (about three) over the whole run.
Extra space: O(1): a few pointers, no stack, no recursion. The output list is O(n) if collected.
Compare: recursive or stack-based traversals use O(h), which is up to O(n) for a skewed tree.
Other Ways Without a Stack
Method
Requirement
Space
Notes
Morris
Tree may be modified temporarily
O(1)
Not safe while other threads read the tree
Parent pointers
Each node stores parent
O(1) extra during traversal, O(n) for the pointers
Walk up to find the successor; common in red-black tree implementations
Permanently threaded tree
Null right pointers store successors, with a flag
O(n) flags
Fast in-order iteration with no per-traversal setup
Level order with a queue
Uses a queue, not a stack
O(w)
Technically satisfies “no recursion or stack” but is not O(1)
Edge Cases
Empty tree: returns [].
Only right children: no threads are created; it is a simple walk.
Only left children: each node creates one thread; still O(n).
Early exit: if you stop in the middle, threads remain and the tree is corrupted. Finish the loop, or only break right after removing a thread.
Concurrent readers: temporary cycles make the tree unsafe to share during the traversal.
Interview Tips
Name Morris traversal, explain the predecessor thread in one sentence, and stress that the tree is restored.
State the trade-off: O(1) space in exchange for temporary mutation and a higher constant factor.
Common follow-ups: Morris pre-order (visit when creating the thread), or using Morris to find the kth smallest element or to recover a BST with two swapped nodes in O(1) space.
25
Explain the Breadth-First Search (BFS) traversing method.
KnownRevise
Breadth-First Search (BFS) explores nodes in order of their distance from the start: first the start node, then all nodes one edge away, then all nodes two edges away, and so on. It uses a FIFO queue: take a node from the front, process it, and add its unvisited neighbours to the back. On a tree, BFS from the root is level-order traversal; on unweighted graphs it finds shortest paths in number of edges.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Algorithm
Put the start node in a queue (and, for graphs, mark it visited).
While the queue is not empty:
Dequeue the front node and process it.
Enqueue each child (tree) or each unvisited neighbour (graph), marking it visited when enqueued.
To handle levels separately, record the queue length at the start of each level and process exactly that many nodes.
Trees need no visited set because there are no cycles and each node has one parent; graphs do.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def level_order(root: Node | None) -> list[list[int]]:
"""BFS on a binary tree, grouped by level."""
levels: list[list[int]] = []
queue: deque[Node] = deque([root] if root else [])
while queue:
level_size = len(queue)
level: list[int] = []
for _ in range(level_size):
node = queue.popleft()
level.append(node.value)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
def shortest_path_length(graph: dict[str, list[str]], start: str, goal: str) -> int:
"""Fewest edges from start to goal in an unweighted graph; -1 if unreachable."""
if start == goal:
return 0
visited = {start}
queue: deque[tuple[str, int]] = deque([(start, 0)])
while queue:
node, distance = queue.popleft()
for neighbour in graph.get(node, []):
if neighbour == goal:
return distance + 1
if neighbour not in visited:
visited.add(neighbour)
queue.append((neighbour, distance + 1))
return -1
tree = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(level_order(tree)) # [[1], [2, 3], [4, 5, 6]]
network = {"A": ["B", "C"], "B": ["D"], "C": ["D", "E"], "D": ["F"], "E": ["F"], "F": []}
print(shortest_path_length(network, "A", "F")) # 3
print(shortest_path_length(network, "F", "A")) # -1
Walkthrough of level_order
Level
Queue at start
Processed
Enqueued
0
[1]
1
2, 3
1
[2, 3]
2, 3
4, 5, 6
2
[4, 5, 6]
4, 5, 6
none
Complexity
Time: O(n) for a tree; O(V + E) for a graph, since each vertex is enqueued once and each edge examined once (twice for undirected graphs).
Space: O(w) for the queue, where w is the maximum number of nodes on one level (the width). In a perfect binary tree the last level holds about n/2 nodes, so BFS needs O(n) space there. Graphs also need O(V) for the visited set. No recursion. Output lists add O(n).
collections.deque gives O(1) popleft(); list.pop(0) would make BFS O(n²).
Applications
Problem
Why BFS
Shortest path in an unweighted graph or grid
First time a node is reached is via a shortest path
For weighted shortest paths, BFS is not enough; use Dijkstra’s algorithm (non-negative weights) or 0-1 BFS for weights 0 and 1.
Edge Cases
Empty tree: returns [].
Start equals goal: distance 0.
Unreachable goal or disconnected graph: returns −1; run BFS from every unvisited node to cover all components.
Cycles: handled by the visited set; forgetting it loops forever.
Very wide trees or graphs: the queue can hold a large fraction of all nodes.
Interview Tips
Say “queue, level by level, shortest path in edges”.
Mark nodes visited when enqueuing, not when dequeuing, or the same node can be enqueued many times.
Common follow-ups: binary tree right side view, word ladder, shortest path in a binary matrix, and BFS versus DFS memory use.
26
Explain the Depth-First Search (DFS) algorithm.
KnownRevise
Depth-First Search (DFS) explores as far as possible along one branch before backtracking to try the next. It uses a stack, either the call stack (recursion) or an explicit one. On a tree, DFS from the root produces pre-order, in-order or post-order traversals depending on when each node is processed; on a graph it needs a visited set to avoid revisiting nodes through cycles. DFS is the basis of cycle detection, topological sorting, connected components, path finding and backtracking.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Algorithm
Push the start node onto a stack.
While the stack is not empty:
Pop a node. In a graph, skip it if already visited; otherwise mark it visited.
Process it, then push its children or unvisited neighbours.
Recursively: process the node, then call DFS on each child or unvisited neighbour.
The difference from BFS is only the container: a stack (last in, first out) goes deep; a queue (first in, first out) goes wide.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def root_to_leaf_paths(root: Node | None) -> list[list[int]]:
"""DFS on a tree: every root-to-leaf path, using an explicit stack of (node, path)."""
paths: list[list[int]] = []
stack = [(root, [root.value])] if root else []
while stack:
node, path = stack.pop()
if node.left is None and node.right is None:
paths.append(path)
for child in (node.right, node.left):
if child:
stack.append((child, path + [child.value]))
return paths
def has_cycle(graph: dict[str, list[str]]) -> bool:
"""DFS on a directed graph with three colours: unvisited, on the current path, finished."""
state = {node: 0 for node in graph} # 0 = new, 1 = on stack, 2 = done
for start in graph:
if state[start]:
continue
stack = [(start, iter(graph[start]))]
state[start] = 1
while stack:
node, neighbours = stack[-1]
neighbour = next(neighbours, None)
if neighbour is None:
state[node] = 2
stack.pop()
elif state.get(neighbour, 0) == 1:
return True # back edge to a node on the current path
elif state.get(neighbour, 0) == 0:
state[neighbour] = 1
stack.append((neighbour, iter(graph.get(neighbour, []))))
return False
tree = Node(1, Node(2, Node(4), Node(5)), Node(3, None, Node(6)))
print(root_to_leaf_paths(tree)) # [[1, 2, 4], [1, 2, 5], [1, 3, 6]]
print(has_cycle({"a": ["b"], "b": ["c"], "c": []})) # False
print(has_cycle({"a": ["b"], "b": ["c"], "c": ["a"]})) # True
The graph version keeps an iterator per stack frame, which is how recursion remembers “which neighbour comes next”. That makes it a faithful iterative DFS, needed for cycle detection where a node must stay “on the path” until all its neighbours are finished.
Walkthrough of root_to_leaf_paths
Pop
Path
Leaf?
Push
1
[1]
no
3 with [1, 3], then 2 with [1, 2]
2
[1, 2]
no
5, then 4
4
[1, 2, 4]
yes
record
5
[1, 2, 5]
yes
record
3
[1, 3]
no
6
6
[1, 3, 6]
yes
record
Complexity
Time: O(n) on a tree; O(V + E) on a graph.
Space: O(h) for the stack on a tree, where h is the height (log n balanced, up to n skewed); O(V) on a graph for the visited state and the stack. The path-copying above adds O(h) per stored path, so collecting all paths costs O(n · h) in the worst case.
Recursive DFS in Python fails beyond about 1,000 levels unless the limit is raised; the explicit stack avoids that.
Applications
Problem
DFS feature used
Tree traversals, path sums, LCA
Exploring one root-to-leaf path at a time
Cycle detection (directed graphs)
“On current path” state
Topological sort
Post-order finishing times
Connected components, flood fill, number of islands
Explore everything reachable
Backtracking (permutations, N-Queens, Sudoku)
Deep search with undo on return
Strongly connected components (Tarjan, Kosaraju)
DFS order and low-link values
Maze solving
Follow a corridor to its end
DFS does not find shortest paths in general; the first path it finds can be long.
Edge Cases
Empty tree: no paths.
Disconnected graph: loop over all start nodes, as has_cycle does.
Self-loop (a → a): detected as a cycle.
Undirected graphs: for cycle detection, ignore the edge back to the parent.
Interview Tips
Say “stack, go deep, backtrack”, and contrast it with BFS’s queue.
Know both recursive and iterative forms, and the three-state colouring for directed cycle detection.
A common mistake is using a single visited set for directed cycle detection, which wrongly reports cycles when two paths reach the same node.
27
What are the key differences between BFS and DFS?
KnownRevise
BFS explores level by level with a queue, so it reaches nodes in order of distance and finds shortest paths in unweighted graphs. DFS explores one branch to the end with a stack (or recursion), then backtracks, which suits exhaustive searches, cycle detection, topological sorting and tree computations that combine children’s results. Both run in O(V + E) time (O(n) on a tree); they differ in order, memory profile and which problems they solve naturally.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
BFS
DFS
Container
Queue (FIFO)
Stack (LIFO) or recursion
Order on a tree
Level order
Pre-, in- or post-order
Shortest path (unweighted)
Yes: first arrival is shortest
No
Memory on a tree
O(w): widest level; up to about n/2 for a perfect tree
O(h): height; about log n balanced, up to n skewed
Memory on a graph
O(V) visited plus a frontier that can be very wide
O(V) visited plus a path-length stack
Finds a target near the start
Fast
May explore deep branches first
Finds a target deep down
Visits every shallower node first
Can reach it quickly
Complete on infinite or huge graphs
Yes, if the branching factor is finite
Can follow an infinite branch forever (fix with depth limits)
Finding the shallowest leaf (minimum depth) shows the difference: BFS stops at the first leaf it meets, while DFS must explore every path to be sure.
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
value: int
left: Node | None = None
right: Node | None = None
def min_depth_bfs(root: Node | None) -> tuple[int, int]:
"""Return (minimum depth counted in nodes, nodes visited)."""
if root is None:
return 0, 0
queue = deque([(root, 1)])
visited = 0
while queue:
node, depth = queue.popleft()
visited += 1
if node.left is None and node.right is None:
return depth, visited
queue.extend((child, depth + 1) for child in (node.left, node.right) if child)
return 0, visited
def min_depth_dfs(root: Node | None) -> tuple[int, int]:
"""Same answer with DFS; must examine every root-to-leaf path."""
if root is None:
return 0, 0
best = float("inf")
visited = 0
stack = [(root, 1)]
while stack:
node, depth = stack.pop()
visited += 1
if node.left is None and node.right is None:
best = min(best, depth)
stack.extend((child, depth + 1) for child in (node.right, node.left) if child)
return int(best), visited
def deep_left_tree(depth: int) -> Node:
"""A long left chain whose root also has a single right leaf."""
root = Node(0, right=Node(-1))
node = root
for value in range(1, depth):
node.left = Node(value)
node = node.left
return root
tree = deep_left_tree(1000)
print(min_depth_bfs(tree)) # (2, 3)
print(min_depth_dfs(tree)) # (2, 1001)
BFS answers after visiting 3 nodes; DFS visits all 1,001, because it cannot know the long left chain has no shallower leaf until it has explored it.
Complexity
BFS
DFS
Time
O(V + E); O(n) on trees
O(V + E); O(n) on trees
Space
O(w) frontier (+ O(V) visited on graphs)
O(h) stack (+ O(V) visited on graphs)
For a perfect binary tree with a million nodes, BFS’s queue peaks around 500,000 entries while DFS’s stack stays near 20. For a skewed tree it is the reverse: BFS holds one node, DFS holds the whole chain.
Choosing
“Shortest”, “minimum number of steps”, “nearest”, “level”: BFS.
Huge or infinite search spaces where the goal is shallow: BFS, or iterative deepening DFS, which combines DFS’s memory with BFS’s shortest-depth guarantee.
Weighted shortest paths: neither; use Dijkstra or Bellman-Ford.
Edge Cases
Disconnected graphs: both need an outer loop over unvisited nodes.
Cycles: both need a visited set on graphs.
Empty input: both return immediately.
Interview Tips
Give the one-line contrast: queue and levels versus stack and depth, then the memory trade-off O(w) versus O(h).
Interviewers often ask which to use for a specific problem; tie the choice to “shortest” versus “explore everything”.
A frequent mistake is claiming DFS always uses less memory; it depends on the shape (skewed trees reverse the comparison).
28
Why does Breadth-First Search use more memory than Depth-First Search?
KnownRevise
BFS must keep the whole frontier in its queue: every node discovered on the current level (and part of the next) waits there until it is processed. DFS only keeps one path from the root to the current node, plus the not-yet-explored siblings along that path. In typical trees, levels get wider much faster than paths get longer: a perfect binary tree with n nodes has a last level of about n/2 nodes but a height of only about log₂ n. So BFS needs O(w) memory (width) while DFS needs O(h) (height), and for bushy trees w is far larger than h.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Numbers for a Perfect Binary Tree
Nodes n
Height h
Widest level w = (n + 1)/2
BFS queue peak
DFS stack peak
15
3
8
about 8
about 4
1,023
9
512
about 512
about 10
~1 million
19
~524,000
~524,000
~20
With branching factor b and depth d, BFS can hold about b^d nodes at once, while DFS holds about b · d (the siblings pushed at each level of the current path). Exponential versus linear in depth is the core reason.
It Depends on Shape
The claim “BFS uses more memory” is about typical, bushy trees. Shape can reverse it:
Shape
BFS (width)
DFS (height)
Uses more
Perfect or complete tree
~n/2
~log n
BFS
Degenerate chain
1
n
DFS
Wide, shallow tree (one root, many children)
n − 1
1
BFS
Random BST
O(n) on its widest levels
O(log n) expected
BFS
Code Example
The function measures the peak size of each container on two shapes.
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
left: Node | None = None
right: Node | None = None
def perfect_tree(height: int) -> Node | None:
"""Build a perfect binary tree level by level."""
if height < 0:
return None
root = Node()
level = [root]
for _ in range(height):
next_level = []
for node in level:
node.left, node.right = Node(), Node()
next_level += [node.left, node.right]
level = next_level
return root
def chain(length: int) -> Node:
root = node = Node()
for _ in range(length - 1):
node.left = Node()
node = node.left
return root
def peak_bfs(root: Node | None) -> int:
queue, peak = deque([root] if root else []), 0
while queue:
peak = max(peak, len(queue))
node = queue.popleft()
queue.extend(child for child in (node.left, node.right) if child)
return peak
def peak_dfs(root: Node | None) -> int:
stack, peak = [root] if root else [], 0
while stack:
peak = max(peak, len(stack))
node = stack.pop()
stack.extend(child for child in (node.right, node.left) if child)
return peak
bushy = perfect_tree(9) # 1,023 nodes
print(peak_bfs(bushy), peak_dfs(bushy)) # 512 10
skewed = chain(1023)
print(peak_bfs(skewed), peak_dfs(skewed)) # 1 1
On the perfect tree BFS holds 512 nodes at its peak while DFS holds 10. On the chain both hold just one, because this iterative DFS pops each node before pushing its only child; a recursive DFS on the same chain would keep 1,023 frames on the call stack, which is where DFS’s O(h) cost shows up (and why Python raises RecursionError at about 1,000).
Why DFS’s Stack Stays Small
When DFS pops a node, it pushes at most two children, then immediately continues with one of them. At any moment the stack holds the pending right siblings along the current root-to-node path: at most one per level, so about h + 1 entries in a binary tree.
Why BFS’s Queue Grows
BFS does not go deeper until every node of the current level has been dequeued, and each of those enqueues its children first. Just before the last level starts, the queue holds the entire last level.
Practical Consequences
Memory-limited searches (game trees, puzzle solvers) use DFS or iterative deepening DFS, which keeps DFS’s O(b · d) memory while still finding the shallowest solution, at the cost of re-exploring upper levels.
Bidirectional BFS cuts the frontier from about b^d to about 2 · b^(d/2) when both start and goal are known.
Graph BFS also needs a visited set of O(V), and so does graph DFS; the difference lies in the frontier.
Complexity Summary
Time
Extra space
BFS
O(n) / O(V + E)
O(w) frontier
DFS
O(n) / O(V + E)
O(h) path
Interview Tips
Answer with “frontier versus path” and the perfect-tree numbers (n/2 versus log n).
Then show you know the exception: a skewed tree makes DFS’s recursion the larger one.
Mention iterative deepening as the standard way to get BFS’s guarantees with DFS’s memory.
29
Illustrate the difference in Peak Memory Consumption between DFS and BFS.
KnownRevise
Peak memory is the largest number of pending nodes a traversal holds at one time. For BFS that is the widest frontier (queue size), for DFS it is the deepest path plus pending siblings (stack size, or recursion depth). Measuring both on different tree shapes makes the difference concrete: on bushy trees BFS’s peak is about n/2 while DFS’s is about log n; on deep, narrow trees the situation reverses.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Queue and Stack Over Time (Perfect Tree, Height 3, 15 Nodes)
Step
BFS queue size
DFS stack size
Start
1
1
After level 0 / first pop
2
2
After level 1
4
3
After level 2
8 (the whole last level)
4 (one pending sibling per level)
End
0
0
BFS’s queue doubles each level; DFS’s stack grows by about one per level.
Code Example
The script measures peak BFS queue length, peak iterative DFS stack length and peak recursion depth on four shapes.
from __future__ import annotations
import random
from collections import deque
from dataclasses import dataclass, field
@dataclass
class Node:
children: list[Node] = field(default_factory=list)
def perfect(height: int, branching: int = 2) -> Node:
root = Node()
level = [root]
for _ in range(height):
next_level = []
for node in level:
node.children = [Node() for _ in range(branching)]
next_level += node.children
level = next_level
return root
def chain(length: int) -> Node:
root = node = Node()
for _ in range(length - 1):
node.children = [Node()]
node = node.children[0]
return root
def star(leaves: int) -> Node:
return Node([Node() for _ in range(leaves)])
def random_tree(size: int, seed: int = 7) -> Node:
rng = random.Random(seed)
nodes = [Node()]
for _ in range(size - 1):
parent = rng.choice(nodes)
child = Node()
parent.children.append(child)
nodes.append(child)
return nodes[0]
def peaks(root: Node) -> tuple[int, int, int]:
"""Return (BFS queue peak, iterative DFS stack peak, recursion depth peak)."""
queue, bfs_peak = deque([root]), 0
while queue:
bfs_peak = max(bfs_peak, len(queue))
queue.extend(queue.popleft().children)
stack, dfs_peak = [root], 0
while stack:
dfs_peak = max(dfs_peak, len(stack))
stack.extend(reversed(stack.pop().children))
depth_peak = 0
frames = [(root, 1)] # simulate recursion depth without recursing
while frames:
node, depth = frames.pop()
depth_peak = max(depth_peak, depth)
frames.extend((child, depth + 1) for child in node.children)
return bfs_peak, dfs_peak, depth_peak
shapes = {
"perfect binary, 1023 nodes": perfect(9),
"chain, 1023 nodes": chain(1023),
"star, 1023 nodes": star(1022),
"random tree, 1023 nodes": random_tree(1023),
}
for name, root in shapes.items():
print(name, peaks(root))
# perfect binary, 1023 nodes (512, 10, 10)
# chain, 1023 nodes (1, 1, 1023)
# star, 1023 nodes (1022, 1022, 2)
# random tree, 1023 nodes (219, 38, 15)
Reading the Results
Shape
BFS peak
DFS stack peak
Recursion depth
Lesson
Perfect binary
512
10
10
Bushy trees: BFS holds half the tree
Chain
1
1
1,023
Deep trees: recursive DFS is the problem, beyond Python’s ~1,000 limit
Star
1,022
1,022
2
Very wide nodes: both containers hold all children at once
Random tree
219
38
15
Typical data: BFS still several times larger
The star shows that iterative DFS also pushes all children of a node at once, so its peak is about h × (branching factor), not just h. Recursive DFS (or an iterator-per-frame stack) holds one frame per level instead.
Formulas
Traversal
Peak memory
BFS
O(w): the widest level, b^d for a full b-ary tree at depth d
Iterative DFS (push all children)
O(b · h)
Recursive DFS / iterator per frame
O(h) frames
For a million-node perfect binary tree, that is about 500,000 queued nodes for BFS against about 20 frames for DFS. Each pending entry costs at least a pointer (8 bytes) plus container overhead, so the BFS frontier there needs several megabytes while the DFS stack fits in a few hundred bytes.
Complexity
Each measurement visits every node once: O(n) time per traversal. Space is the peak being measured: O(w) for BFS, O(b · h) for the iterative stack, O(h) for the simulated recursion. The script never recurses, so the 1,023-deep chain is safe.
Interview Tips
Draw the queue doubling per level versus the stack growing by one per level; it is the clearest illustration.
Mention the exceptions: a chain makes recursion deep, and very high branching makes both containers large.
A common follow-up is how to get BFS’s shortest-path guarantee with DFS memory: iterative deepening DFS.
30
Provide some practical examples of using Depth-First Search vs Breadth-First Search.
KnownRevise
Use BFS when the question is about distance or the nearest something: shortest routes in unweighted networks, degrees of separation, nearest exit in a grid, crawling pages closest to a seed. Use DFS when you must explore everything reachable or follow dependencies: build order (topological sort), cycle and deadlock detection, maze and puzzle solving with backtracking, disk-usage totals for a directory, and connected regions.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Practical Examples
Scenario
Choice
Why
“People you may know” (friends of friends)
BFS
Distance 2 in a social graph; stop at the second level
Fewest moves in a grid or board game
BFS
First arrival is a shortest path
Web crawler limited to depth 3
BFS
Visits close pages first, respects the depth limit
Network broadcast or nearest server
BFS
Expands by hop count
Minimum depth or right-side view of a tree
BFS
Works level by level
Build systems, package installation order
DFS
Post-order gives a topological order
Detecting circular imports or lock cycles
DFS
Back edges reveal cycles
Solving Sudoku, N-Queens, generating permutations
DFS (backtracking)
Explore a choice deeply, undo, try the next
Total size of a folder
DFS (post-order)
A folder’s size needs its children’s sizes
Counting islands or flood fill
DFS (or BFS)
Any full exploration works; DFS is shortest to write
Strongly connected components
DFS
Tarjan’s and Kosaraju’s algorithms rely on DFS order
Garbage collector mark phase
Either
Reachability only; implementations pick by memory behaviour
Code Example
BFS finds the fewest steps through a grid; DFS computes a safe build order and rejects cycles.
from collections import deque
def fewest_steps(grid: list[str], start: tuple[int, int], goal: tuple[int, int]) -> int:
"""BFS on a grid where '#' is a wall; returns -1 if the goal is unreachable."""
rows, cols = len(grid), len(grid[0])
queue = deque([(start, 0)])
visited = {start}
while queue:
(row, col), steps = queue.popleft()
if (row, col) == goal:
return steps
for d_row, d_col in ((1, 0), (-1, 0), (0, 1), (0, -1)):
nxt = (row + d_row, col + d_col)
if 0 <= nxt[0] < rows and 0 <= nxt[1] < cols and grid[nxt[0]][nxt[1]] != "#" and nxt not in visited:
visited.add(nxt)
queue.append((nxt, steps + 1))
return -1
def build_order(dependencies: dict[str, list[str]]) -> list[str]:
"""DFS topological sort: each target appears after everything it depends on."""
order: list[str] = []
state: dict[str, int] = {} # 1 = in progress, 2 = done
for target in dependencies:
if state.get(target):
continue
stack = [(target, iter(dependencies.get(target, [])))]
state[target] = 1
while stack:
node, deps = stack[-1]
dep = next(deps, None)
if dep is None:
state[node] = 2
order.append(node)
stack.pop()
elif state.get(dep) == 1:
raise ValueError(f"dependency cycle through {dep}")
elif not state.get(dep):
state[dep] = 1
stack.append((dep, iter(dependencies.get(dep, []))))
return order
maze = ["..#.",
".##.",
"....",
"#.#."]
print(fewest_steps(maze, (0, 0), (0, 3))) # 7
deps = {"app": ["lib", "config"], "lib": ["utils"], "config": [], "utils": []}
print(build_order(deps)) # ['utils', 'lib', 'config', 'app']
try:
build_order({"a": ["b"], "b": ["a"]})
except ValueError as error:
print(error) # dependency cycle through a
Walkthrough of the Grid Search
From (0, 0) BFS expands in rings: distance 1 reaches (1, 0) and (0, 1); the wall column forces the path down to row 2, across, and back up the right edge: (0,0) → (1,0) → (2,0) → (2,1) → (2,2) → (2,3) → (1,3) → (0,3), 7 steps. Because BFS explores by distance, the first time it reaches (0, 3) is guaranteed to be the minimum.
Complexity
Grid BFS: O(R × C) time and space for the visited set and queue.
Topological DFS: O(V + E) time, O(V) space for the state map, stack and output.
Neither recurses, so large inputs do not hit Python’s recursion limit.
Edge Cases
Start equals goal: 0 steps.
Start or goal on a wall, or enclosed: BFS returns −1 (add an explicit wall check if needed).
Dependencies that are not keys ("utils" missing from the dict) are treated as having no dependencies.
Disconnected targets: the outer loop in build_order covers every target.
Interview Tips
Map the problem’s wording to the algorithm: “minimum”, “shortest”, “nearest” → BFS; “all”, “order”, “cycle”, “any path” → DFS.
For weighted graphs (road distances in kilometres), neither is correct; use Dijkstra.
A frequent mistake is solving a shortest-path grid problem with DFS and returning the first path found, which is not necessarily the shortest.
31
Implement an Insert Function for a Binary Search Tree (BST).
KnownRevise
To insert a key into a BST, walk down from the root as if searching for it: go left when the key is smaller than the current node, right when it is larger. When the walk reaches an empty child slot, attach a new leaf there. The new node is always a leaf, the BST ordering is preserved automatically, and the cost is O(h), the height of the tree.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Algorithm
If the tree is empty, the new node becomes the root.
Otherwise start at the root and keep a reference to the current node.
Compare the key:
Smaller: if left is empty, attach the new node there; otherwise move left.
Larger: same on the right.
Equal: apply the duplicate policy (here: reject and return False).
Return the (possibly new) root, or a success flag.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
class BST:
"""Binary search tree with an iterative insert (no duplicates)."""
def __init__(self) -> None:
self.root: Node | None = None
self.size = 0
def insert(self, key: int) -> bool:
"""Insert key; return True if added, False if it was already present."""
if self.root is None:
self.root = Node(key)
self.size = 1
return True
current = self.root
while True:
if key < current.key:
if current.left is None:
current.left = Node(key)
break
current = current.left
elif key > current.key:
if current.right is None:
current.right = Node(key)
break
current = current.right
else:
return False # duplicate
self.size += 1
return True
def inorder(self) -> list[int]:
result, stack, node = [], [], self.root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.key)
node = node.right
return result
def insert_recursive(node: Node | None, key: int) -> Node:
"""Recursive version: returns the root of the updated subtree."""
if node is None:
return Node(key)
if key < node.key:
node.left = insert_recursive(node.left, key)
elif key > node.key:
node.right = insert_recursive(node.right, key)
return node
tree = BST()
for key in [50, 30, 70, 20, 40, 60, 80, 35]:
tree.insert(key)
print(tree.inorder()) # [20, 30, 35, 40, 50, 60, 70, 80]
print(tree.insert(40)) # False
print(tree.size) # 8
root = None
for key in [5, 2, 8, -1]:
root = insert_recursive(root, key)
print(root.left.left.key) # -1
Time: O(h). Best case O(1) when inserting into an empty tree or directly under the root; average O(log n) for random insertion orders; worst case O(n) when keys arrive sorted and the tree becomes a chain.
Space: O(1) extra for the iterative version; O(h) call stack for the recursive version, which can exceed Python’s recursion limit (about 1,000) on a degenerate tree. Each insert adds one node, so the tree is O(n).
Duplicate Policies
Policy
How
Trade-off
Reject (shown)
Return False on equal keys
Set semantics
Count
Store count in the node and increment
Multiset with no extra nodes
Always go right (or left)
Treat equal as larger
Simple, but many equal keys form a chain
Update value
Replace the stored value for a map
Map semantics
Edge Cases
Empty tree: the new node becomes the root.
Negative keys: compared normally.
Sorted input: works, but produces height n − 1; use a self-balancing tree (AVL, red-black) when order is not random.
Non-comparable keys: mixing types (for example int and str) raises TypeError in Python.
Interview Tips
Write the iterative version (no recursion limit) and mention the duplicate policy before coding.
State that the new node is always a leaf, so no existing links need restructuring in a plain BST.
A common follow-up is “insert into an AVL or red-black tree”, which adds rebalancing on the way back up.
A frequent bug in the recursive version is forgetting to assign the returned subtree (node.left = insert(...)), which silently drops new nodes.
32
Implement a Delete Function for a Binary Search Tree (BST).
KnownRevise
Deleting from a BST first finds the node, then handles one of three cases while keeping the ordering: a leaf is simply removed; a node with one child is replaced by that child; a node with two children takes the key of its in-order successor (the smallest key in its right subtree), and that successor, which has no left child, is removed instead. Every case costs O(h).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Three Cases
Case 1, leaf (delete 20): Case 2, one child (delete 30): Case 3, two children (delete 50):
50 50 50 50 50 60
/ \ / \ / \ / \ / \ / \
30 70 → 30 70 30 70 → 40 70 40 70 → 40 70
/ \ / \ \
20 40 60 80 80
Case 1: set the parent’s pointer to None.
Case 2: link the parent directly to the only child.
Case 3: the successor 60 is the leftmost node of the right subtree. Copy 60 into the node being deleted, then delete the original 60, which has at most a right child (case 1 or 2).
The in-order predecessor (largest key in the left subtree) works equally well.
Code Example
from __future__ import annotations
import random
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def insert(root: Node | None, key: int) -> Node:
"""Iterative insert, ignoring duplicates."""
if root is None:
return Node(key)
node = root
while key != node.key:
side = "left" if key < node.key else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, Node(key))
break
node = child
return root
def delete(root: Node | None, key: int) -> Node | None:
"""Delete key from the BST iteratively and return the (possibly new) root."""
parent, node = None, root
while node and node.key != key:
parent, node = node, (node.left if key < node.key else node.right)
if node is None:
return root # key not found
if node.left and node.right: # case 3: two children
successor_parent, successor = node, node.right
while successor.left:
successor_parent, successor = successor, successor.left
node.key = successor.key
parent, node = successor_parent, successor # now delete the successor
child = node.left or node.right # cases 1 and 2: at most one child
if parent is None:
return child
if parent.left is node:
parent.left = child
else:
parent.right = child
return root
def inorder(root: Node | None) -> list[int]:
result, stack, node = [], [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.key)
node = node.right
return result
root = None
for key in [50, 30, 70, 20, 40, 60, 80]:
root = insert(root, key)
root = delete(root, 20) # leaf
root = delete(root, 30) # one child (40)
root = delete(root, 50) # two children: successor 60 moves up
print(inorder(root), root.key) # [40, 60, 70, 80] 60
print(inorder(delete(root, 99))) # [40, 60, 70, 80] (missing key: unchanged)
# Randomised check against a Python set
rng = random.Random(1)
root, reference = None, set()
for _ in range(2000):
key = rng.randint(0, 60)
if rng.random() < 0.5:
root = insert(root, key)
reference.add(key)
else:
root = delete(root, key)
reference.discard(key)
print(inorder(root) == sorted(reference)) # True
Walkthrough: delete(root, 50) After the First Two Deletions
Step
State
Tree
50 with left 40, right 70 (70 has children 60, 80)
Find
50 is the root, so parent = None
Two children
Successor search: 70 → left 60, which has no left child
Copy
Root key becomes 60
Remove successor
60‘s parent is 70; 70.left = None (60 had no right child)
Result
Root 60, left 40, right 70 → 80
Complexity
Time: O(h): one walk down to find the node and, for case 3, a continued walk to the successor. Average O(log n) for random trees, worst case O(n) for a degenerate tree.
Space: O(1) extra in this iterative version; a recursive version uses O(h) call stack.
Edge Cases
Empty tree or missing key: returns the tree unchanged.
Deleting the root: handled by returning the new root (its only child, or the root with the successor’s key).
Single-node tree: deleting it returns None.
Successor is the right child itself (it has no left child): handled because successor_parent is the node being deleted, and the code updates parent.right.
Duplicates: this tree rejects them; with a count field, decrement instead of removing while the count is above 1.
Common Pitfalls
Forgetting the case where the root is deleted, so the caller keeps a stale reference.
Copying the successor’s key but forgetting to delete the original successor node.
Assuming the successor is always a left child; it is the right child when the right subtree has no left branch.
Copying keys is fine for a simple BST, but if other code holds references to nodes, relink the successor node instead of copying its key.
Interviewers often ask why the successor has no left child (it is the leftmost node) and how deletion changes in AVL or red-black trees (rebalancing after removal).
33
How do you Search for a value in a Binary Search Tree (BST)?
KnownRevise
Start at the root and compare the target with the current node’s key: if they are equal, you have found it; if the target is smaller, continue in the left subtree; if larger, continue in the right subtree. If you reach an empty child, the value is not in the tree. Each comparison discards a whole subtree, so search costs O(h): O(log n) for a balanced tree, O(n) for a degenerate one.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Why It Works
The BST invariant says every key in a node’s left subtree is smaller and every key in its right subtree is larger. If the target is less than the node’s key, it cannot be anywhere on the right, so ignoring that subtree is safe. The search follows exactly one root-to-leaf path.
Code Example
The same descent also answers floor (largest key ≤ target) and ceiling (smallest key ≥ target) queries, which a hash table cannot do.
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def search(root: Node | None, target: int) -> Node | None:
"""Iterative BST search; returns the node or None."""
node = root
while node is not None and node.key != target:
node = node.left if target < node.key else node.right
return node
def search_recursive(node: Node | None, target: int) -> Node | None:
"""Recursive version; depth equals the path length."""
if node is None or node.key == target:
return node
if target < node.key:
return search_recursive(node.left, target)
return search_recursive(node.right, target)
def floor_and_ceiling(root: Node | None, target: int) -> tuple[int | None, int | None]:
"""Largest key <= target and smallest key >= target, in one descent."""
floor = ceiling = None
node = root
while node:
if node.key == target:
return target, target
if target < node.key:
ceiling = node.key
node = node.left
else:
floor = node.key
node = node.right
return floor, ceiling
# 8
# / \
# 3 10
# / \ \
# 1 6 14
# / \ /
# 4 7 13
root = Node(8, Node(3, Node(1), Node(6, Node(4), Node(7))), Node(10, None, Node(14, Node(13))))
print(search(root, 7).key) # 7
print(search(root, 5)) # None
print(search_recursive(root, 13).key) # 13
print(floor_and_ceiling(root, 5)) # (4, 6)
print(floor_and_ceiling(root, 15)) # (14, None)
Walkthrough: Searching for 5
Step
Node
Comparison
Move
1
8
5 < 8
left
2
3
5 > 3
right
3
6
5 < 6
left
4
4
5 > 4
right → empty
5
—
reached None
not found
On the way, the last key smaller than 5 was 4 and the last key larger was 6, which is exactly what floor_and_ceiling returns.
Complexity
Case
Time
When
Best
O(1)
Target is the root
Average
O(log n)
Random insertion order or balanced tree
Worst
O(n)
Degenerate tree (keys inserted in sorted order)
Space: O(1) for the iterative version; O(h) call stack for the recursive one. The tree itself is O(n).
A balanced BST with a million keys needs about 20 comparisons; a degenerate one may need a million.
Search Versus Other Structures
Structure
Exact lookup
Floor/ceiling, range
Ordered iteration
Balanced BST
O(log n)
O(log n) (+ k results)
O(n)
Hash table
O(1) average, O(n) worst
Not supported efficiently
No
Sorted array with binary search
O(log n)
O(log n)
O(n)
Sorted arrays search just as fast but insert in O(n); BSTs keep O(log n) inserts when balanced.
Edge Cases
Empty tree: returns None.
Target smaller or larger than every key: the walk ends at the leftmost or rightmost leaf; floor or ceiling is None.
Duplicates: if your policy stores equal keys on one side, a search finds the first one; searching for all copies needs to continue on that side.
Mixed types: comparing incomparable keys raises TypeError in Python.
Interview Tips
Write the iterative loop; it is three lines and has no recursion-depth risk.
Mention that the cost is O(h), not automatically O(log n).
Common follow-ups: floor and ceiling, closest value to a target, in-order successor, and searching in a BST rotated or stored as an array.
34
What are the time complexities of BST insert, search and delete, and why?
KnownRevise
All three operations are O(h), where h is the height of the tree, because each one follows a single path from the root downward, making one comparison per level. How large h is depends on the tree’s shape: O(log n) when the tree is balanced (or built from keys in random order), but O(n) in the worst case, when keys are inserted in sorted order and the tree degenerates into a chain. Self-balancing BSTs (AVL, red-black) guarantee O(log n) in the worst case.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Summary
Operation
Best
Average (random BST)
Worst (degenerate)
Balanced BST worst case
Why
Search
O(1)
O(log n)
O(n)
O(log n)
One comparison per level along one path
Insert
O(1)
O(log n)
O(n)
O(log n)
Search for the empty slot, attach a leaf
Delete
O(1)
O(log n)
O(n)
O(log n)
Find the node, possibly walk to the successor, relink O(1) pointers
Min / max
O(1)
O(log n)
O(n)
O(log n)
Follow left or right pointers
In-order traversal
O(n)
O(n)
O(n)
O(n)
Visits every node
Space: the tree uses O(n). Iterative operations use O(1) extra; recursive ones use O(h) stack.
Why the Height Varies
Minimum height for n nodes is ⌊log₂ n⌋, because each level can at most double the number of nodes.
Random insertion order gives an expected depth of about 2 ln n ≈ 1.39 log₂ n for a typical node, so average operations are O(log n).
Sorted insertion makes every new key the largest so far, always going right: height n − 1, a linked list.
Delete does not repair shape: many deletions with the successor rule can also skew a tree over time.
Code Example
Count the comparisons a search needs in a tree built from shuffled keys versus sorted keys.
from __future__ import annotations
import random
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def build(keys: list[int]) -> Node | None:
"""Insert keys one by one (iterative, no duplicates)."""
root = None
for key in keys:
if root is None:
root = Node(key)
continue
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))
break
node = child
return root
def comparisons(root: Node | None, target: int) -> int:
"""Number of nodes compared while searching for target."""
count, node = 0, root
while node:
count += 1
if target == node.key:
break
node = node.left if target < node.key else node.right
return count
keys = list(range(2000))
shuffled = keys[:]
random.Random(3).shuffle(shuffled)
random_tree, sorted_tree = build(shuffled), build(keys)
average_random = sum(comparisons(random_tree, k) for k in keys) / len(keys)
average_sorted = sum(comparisons(sorted_tree, k) for k in keys) / len(keys)
print(round(average_random, 1), round(average_sorted, 1)) # 12.9 1000.5
With 2,000 keys, a search in the randomly built tree compares about 13 nodes on average (the expected depth of a random BST grows like 2 ln n), while the sorted build needs about 1,000, half the tree. Building sorted_tree itself took about two million comparisons, the O(n²) cost of n worst-case inserts.
Why Delete Is Still O(h)
Finding the node: one path, O(h).
Two-children case: continue from that node to its in-order successor, still on a single downward path, so the total stays O(h).
Relinking: a constant number of pointer changes.
Guaranteeing O(log n)
Tree
Worst-case height
Extra work per update
AVL
≈ 1.44 log₂ n
Up to O(log n) height updates, O(1) rotations on insert, O(log n) on delete
Red-black
≤ 2 log₂(n + 1)
O(1) amortized recolouring, at most 2 rotations on insert and 3 on delete
Treap / randomised BST
O(log n) expected
Rotations based on random priorities
Splay tree
O(log n) amortized
Rotations on every access
Interview Tips
Answer “O(h)” first, then give the balanced and degenerate values; saying “O(log n)” alone is the classic incomplete answer.
Explain why: one path, one comparison per level.
A common follow-up: “what input makes a BST slow?” Sorted or nearly sorted keys, such as timestamps or auto-increment IDs.
35
What are the advantages and disadvantages of BSTs?
KnownRevise
A binary search tree stores keys in sorted order with dynamic inserts and deletes, so it answers ordered questions (sorted iteration, minimum, floor and ceiling, range queries) that hash tables cannot, and it does so in O(h) per operation. Its weakness is that a plain BST has no balance guarantee: sorted input makes it a linked list with O(n) operations. In practice you use a self-balancing variant (red-black, AVL) or a B-tree, and choose a hash table when you only need exact-key lookups.
Read full answerHide full answer
Applies tolanguage-independent (comparisons apply to C++ `std::map`, Java `TreeMap`, database indexes)
Advantages
Advantage
Detail
Ordered data
In-order traversal yields keys in sorted order in O(n)
Ordered queries
Min, max, floor, ceiling, predecessor, successor in O(h)
Range queries
All keys in [low, high] in O(h + k) for k results
Dynamic updates
Insert and delete without shifting elements, unlike a sorted array
Rank and selection
With subtree sizes stored, kth smallest and rank in O(h)
No resizing
Grows one node at a time; no rehashing pauses
Predictable with balancing
Red-black or AVL trees give O(log n) worst case, unlike hash tables’ O(n) worst case
Sorted or adversarial input gives height n − 1 and O(n) operations
Slower exact lookup than hashing
O(log n) comparisons versus O(1) average for a hash table
Memory overhead
Two child pointers (often a parent pointer and balance data too) per key
Poor cache locality
Nodes scattered in memory; each level can be a cache miss. B-trees and sorted arrays do better
Comparison-based
Keys need a total order; complex keys make comparisons costly
More complex code
Deletion and especially balancing (rotations, colours) are easy to get wrong
Recursion depth
Recursive implementations can overflow on skewed trees
Concurrency
Rebalancing touches several nodes, making fine-grained locking hard
Compared with Alternatives
Need
Balanced BST
Hash table
Sorted array
B+ tree
Exact lookup
O(log n)
O(1) average
O(log n)
O(log n), few disk reads
Insert / delete
O(log n)
O(1) average
O(n)
O(log n)
Sorted iteration
Yes
No (needs a sort)
Yes
Yes, via linked leaves
Range query
O(log n + k)
O(n)
O(log n + k)
O(log n + k)
Memory per key
High (pointers)
Medium (load factor)
Lowest
Medium, page-based
Cache and disk friendliness
Low
Medium
High
High
Worst case
O(log n)
O(n) with many collisions
O(n) for updates
O(log n)
When to Use a BST
You need ordered operations together with frequent updates: leaderboards, schedulers keyed by time, interval scheduling, order books.
You want worst-case guarantees rather than hash table averages.
Data lives in memory; for data on disk, use a B+ tree.
When Not To
Only exact-key lookups: use a hash table (dict, HashMap).
Data is built once and rarely changes: a sorted array with binary search is smaller and faster.
In Python, the standard library has no balanced BST; common choices are dict for exact lookups, bisect on a sorted list for small or read-heavy data, or the third-party sortedcontainers package.
Interview Tips
Lead with the defining strength (order) and the defining weakness (no balance guarantee in a plain BST).
Compare with a hash table and a sorted array; interviewers want to see you choose by operations needed.
A common follow-up: “how do databases index data?” (B+ trees, because of disk pages and range scans).
A frequent mistake is listing O(log n) as a plain BST’s guaranteed complexity; it is O(h).
36
What is an AVL Tree? How do you balance it?
KnownRevise
An AVL tree (named after Adelson-Velsky and Landis) is a self-balancing binary search tree in which, for every node, the heights of the left and right subtrees differ by at most 1. Each node stores its height, and the balance factorheight(left) − height(right) must stay in {−1, 0, +1}. After an insert or delete, nodes on the path back to the root are checked; when one reaches ±2, one or two rotations restore balance. This keeps the height below about 1.44 log₂ n, so search, insert and delete are O(log n) in the worst case.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Four Imbalance Cases
Let z be the lowest node with balance ±2 after an update.
Case
Shape
Fix
Left-Left
Too heavy on the left of the left child
Single right rotation at z
Right-Right
Too heavy on the right of the right child
Single left rotation at z
Left-Right
Left child is right-heavy
Left rotation at the left child, then right rotation at z
Right-Left
Right child is left-heavy
Right rotation at the right child, then left rotation at z
Right-Right (insert 1, 2, 3): after left rotation at 1:
1 2
\ / \
2 1 3
\
3
A rotation changes three pointers, keeps the in-order sequence (so the BST property holds), and reduces the subtree’s height by one.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
height: int = 0
def height(node: Node | None) -> int:
return node.height if node else -1
def update(node: Node) -> None:
node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(y: Node) -> Node:
x = y.left
y.left, x.right = x.right, y
update(y)
update(x)
return x
def rotate_left(x: Node) -> Node:
y = x.right
x.right, y.left = y.left, x
update(x)
update(y)
return y
def rebalance(node: Node) -> Node:
update(node)
balance = height(node.left) - height(node.right)
if balance > 1: # left heavy
if height(node.left.left) < height(node.left.right):
node.left = rotate_left(node.left) # left-right case
return rotate_right(node) # left-left case
if balance < -1: # right heavy
if height(node.right.right) < height(node.right.left):
node.right = rotate_right(node.right) # right-left case
return rotate_left(node) # right-right case
return node
def insert(root: Node | None, key: int) -> Node:
"""Insert key and rebalance along the path back to the root (iterative)."""
path: list[Node] = []
node = root
while node:
if key == node.key:
return root
path.append(node)
node = node.left if key < node.key else node.right
child = Node(key)
while path:
parent = path.pop()
if child.key < parent.key:
parent.left = child
else:
parent.right = child
child = rebalance(parent)
return child
def inorder(root: Node | None) -> list[int]:
result, stack, node = [], [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.key)
node = node.right
return result
root = None
for key in range(1, 8): # sorted input: a plain BST would become a chain
root = insert(root, key)
print(root.key, height(root)) # 4 2
print(inorder(root)) # [1, 2, 3, 4, 5, 6, 7]
root = None
for key in range(1, 1001):
root = insert(root, key)
print(height(root)) # 9
The insert walks down recording the path, attaches the new leaf, then walks back up re-linking each parent and calling rebalance, so there is no recursion.
Walkthrough: Inserting 1 to 7 in Order
Insert
Imbalance
Rotation
Root after
1, 2
none
1
3
1 has balance −2 (Right-Right)
left at 1
2
4
none
2
5
3 has balance −2
left at 3
2
6
2 has balance −2
left at 2
4
7
5 has balance −2
left at 5
4
The result is the perfect tree rooted at 4, height 2. A plain BST would have height 6. For 1,000 sorted keys the AVL height is 9, the minimum possible.
Complexity
Operation
Time
Notes
Search
O(log n)
Height ≤ about 1.44 log₂(n + 2)
Insert
O(log n)
At most one single or double rotation is needed
Delete
O(log n)
May need rotations at several levels, up to O(log n)
Space
O(n)
One height field per node; the insert path list is O(log n)
Edge Cases
Empty tree: the first insert creates the root.
Duplicates: ignored here; use a count field for a multiset.
Sorted input: handled; it triggers rotations but keeps the height logarithmic.
Height convention: empty subtrees have height −1 and leaves 0, so the balance factor arithmetic works.
Interview Tips
State the invariant (difference ≤ 1 at every node), the four cases and that a double rotation is two single rotations.
Mention the height bound (about 1.44 log₂ n) and compare with red-black trees (≤ 2 log₂ n, fewer rotations on updates).
A common bug is forgetting to update heights bottom-up after a rotation: update the lower node first.
37
What is a Red-Black Tree?
KnownRevise
A red-black tree is a self-balancing binary search tree in which every node is coloured red or black, and colour rules limit how unbalanced the tree can get. The rules guarantee that the longest root-to-leaf path is at most twice the shortest, so the height is at most 2 log₂(n + 1) and search, insert and delete run in O(log n) worst case. Updates restore the rules with recolouring and at most a few rotations, which is why red-black trees implement C++ std::map and std::set in common standard libraries, Java TreeMap, and the Linux kernel’s rbtree.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Rules
Every node is red or black.
The root is black.
Every empty leaf (None, often called NIL) counts as black.
A red node cannot have a red child (no two reds in a row).
Every path from a node down to an empty leaf contains the same number of black nodes (the node’s black height).
Why the Height Is Logarithmic
By rule 5, every root-to-leaf path has the same number b of black nodes.
By rule 4, red nodes cannot be adjacent, so a path has at most b red nodes: the longest path is at most 2b, the shortest at least b.
A subtree with black height b contains at least 2^b − 1 internal nodes, so b ≤ log₂(n + 1) and the height is at most 2 log₂(n + 1).
Example
10(B)
/ \
5(B) 20(R)
/ \
15(B) 30(B)
Every path from 10 to an empty leaf passes two black nodes plus the NIL: 10 → 5 → NIL, and 10 → 20 → 15 → NIL both have black count 3 when NIL is counted. Red 20 has only black children.
Code Example
The validator checks rules 4 and 5 and returns the black height (counting NIL leaves as 1).
from __future__ import annotations
from dataclasses import dataclass
RED, BLACK = "R", "B"
@dataclass(eq=False)
class Node:
key: int
color: str = RED
left: Node | None = None
right: Node | None = None
def black_height(node: Node | None) -> int:
"""Validate red-black rules below node; return its black height or raise."""
if node is None:
return 1 # empty leaves count as black
if node.color == RED:
for child in (node.left, node.right):
if child and child.color == RED:
raise ValueError(f"red node {node.key} has a red child")
left, right = black_height(node.left), black_height(node.right)
if left != right:
raise ValueError(f"unequal black heights below {node.key}")
return left + (node.color == BLACK)
valid = Node(10, BLACK, Node(5, BLACK), Node(20, RED, Node(15, BLACK), Node(30, BLACK)))
print(black_height(valid)) # 3
two_reds = Node(10, BLACK, Node(5, BLACK), Node(20, RED, Node(15, RED)))
try:
black_height(two_reds)
except ValueError as error:
print(error) # red node 20 has a red child
Operations
Operation
Time
How balance is restored
Search
O(log n)
No changes; same as a BST
Insert
O(log n)
New node is red; fix red-red conflicts by recolouring up the tree, then at most 2 rotations
Delete
O(log n)
Fix a “double black” deficit with recolouring and at most 3 rotations
Space
O(n)
One colour bit per node (often packed into a pointer)
Validation as written is O(n) time and O(h) recursion depth, which is O(log n) for a valid tree.
Red-Black versus AVL in Brief
Aspect
Red-black
AVL
Balance
Looser: height ≤ 2 log₂(n + 1)
Stricter: height ≤ about 1.44 log₂ n
Lookups
Slightly deeper paths
Slightly faster
Updates
Fewer rotations; O(1) amortized restructuring
More rotations, especially on delete
Typical use
General-purpose library maps
Read-heavy indexes
Edge Cases
Empty tree: valid; black height 1 (just NIL).
Single node: must be black.
All-black trees are valid if perfectly balanced; red nodes give the flexibility to absorb inserts without restructuring.
Duplicate keys: handled by the surrounding map or multiset policy, not by the colour rules.
Interview Tips
List the five rules and explain how rules 4 and 5 bound the height to 2 log₂(n + 1).
Know that inserts colour the new node red (so black heights stay equal) and that fixing involves the uncle’s colour.
A common follow-up is comparing with AVL; another is the link to 2-3-4 trees: a black node with its red children corresponds to one 2-3-4 node.
38
How does Inserting or Deleting nodes affect a Red-Black Tree?
KnownRevise
An ordinary BST insert or delete can break the red-black rules, so each update is followed by a fix-up. Insert adds a red leaf, which keeps every black height equal but may create a red parent with a red child; the fix-up recolours up the tree while the new node’s uncle is red, then finishes with one or two rotations. Delete may remove a black node, leaving a path one black short (a “double black”); its fix-up uses the sibling’s colour and its children, with recolouring and at most three rotations. Both stay O(log n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Insert Fix-Up Cases
Let node be red with a red parent, and grandparent black.
Case
Condition
Action
Continues?
1
Uncle is red
Colour parent and uncle black, grandparent red; move node to the grandparent
Yes, two levels up
2
Uncle black, node is an inner child (zig-zag)
Rotate at the parent to make it an outer child
Becomes case 3
3
Uncle black, node is an outer child (line)
Colour parent black and grandparent red, rotate at the grandparent
No, done
Finally the root is coloured black. Case 1 can repeat up to O(log n) times but only recolours; cases 2 and 3 run at most once, so an insert does at most 2 rotations.
Delete Fix-Up Cases (Summary)
After removing a node (using the in-order successor for two children), if a black node was removed, the child that took its place carries an extra “black” (x). Let sibling be x‘s sibling:
Case
Condition
Action
1
Sibling red
Rotate at the parent and swap colours, giving x a black sibling
2
Sibling black, both its children black
Colour sibling red; move the extra black up to the parent
3
Sibling black, near child red, far child black
Rotate at the sibling to make the far child red
4
Sibling black, far child red
Rotate at the parent, recolour; done
Removing a red node needs no fix-up. Deletion performs at most 3 rotations, while case 2 may recolour up to the root.
Code Example (Insert)
from __future__ import annotations
from dataclasses import dataclass
RED, BLACK = "R", "B"
@dataclass(eq=False)
class Node:
key: int
color: str = RED
left: Node | None = None
right: Node | None = None
parent: Node | None = None
class RedBlackTree:
"""Red-black tree insert with the standard fix-up (no duplicates)."""
def __init__(self) -> None:
self.root: Node | None = None
self.rotations = 0
def _rotate_left(self, x: Node) -> None:
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x is x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left, x.parent = x, y
self.rotations += 1
def _rotate_right(self, y: Node) -> None:
x = y.left
y.left = x.right
if x.right:
x.right.parent = y
x.parent = y.parent
if y.parent is None:
self.root = x
elif y is y.parent.right:
y.parent.right = x
else:
y.parent.left = x
x.right, y.parent = y, x
self.rotations += 1
def insert(self, key: int) -> None:
parent, node = None, self.root
while node:
if key == node.key:
return
parent, node = node, (node.left if key < node.key else node.right)
new = Node(key, parent=parent)
if parent is None:
self.root = new
elif key < parent.key:
parent.left = new
else:
parent.right = new
self._fix_insert(new)
def _fix_insert(self, node: Node) -> None:
while node.parent and node.parent.color == RED:
parent, grandparent = node.parent, node.parent.parent
if parent is grandparent.left:
uncle = grandparent.right
if uncle and uncle.color == RED: # case 1: recolour, move up
parent.color = uncle.color = BLACK
grandparent.color = RED
node = grandparent
else:
if node is parent.right: # case 2: rotate into a line
node = parent
self._rotate_left(node)
parent = node.parent
parent.color, grandparent.color = BLACK, RED # case 3
self._rotate_right(grandparent)
else:
uncle = grandparent.left
if uncle and uncle.color == RED:
parent.color = uncle.color = BLACK
grandparent.color = RED
node = grandparent
else:
if node is parent.left:
node = parent
self._rotate_right(node)
parent = node.parent
parent.color, grandparent.color = BLACK, RED
self._rotate_left(grandparent)
self.root.color = BLACK
tree = RedBlackTree()
for key in range(1, 11):
tree.insert(key)
print(tree.root.key, tree.root.color, tree.rotations) # 4 B 5
Walkthrough: Inserting 1, 2, 3
Step
Tree
Problem
Fix
Insert 1
1
root red
colour black
Insert 2
1(B) → right 2®
none
Insert 3
1(B) → 2® → 3®
red-red, uncle (left of 1) is NIL, black; 3 is an outer child
case 3: colour 2 black, 1 red, rotate left at 1
Result
2(B) with children 1®, 3®
valid
Inserting 1 to 10 in order performs 5 rotations and ends with a black root 4.
Complexity
Insert: O(log n) to find the position, O(log n) recolourings at most, at most 2 rotations. Recolouring is O(1) amortized over a sequence of inserts.
Delete: O(log n), at most 3 rotations.
Space: O(1) extra besides the parent pointers and colour bits; the fix-ups are iterative. The validator is recursive with depth O(log n).
Interview Tips
Say “insert red, fix red-red using the uncle; delete black, fix double-black using the sibling”.
Quote the rotation bounds (2 for insert, 3 for delete); that is why red-black trees are preferred when updates are frequent.
Interviewers rarely expect full delete code; explaining the cases clearly is usually enough.
39
What is the time complexity for Insert into a Red-Black Tree?
KnownRevise
Inserting into a red-black tree takes O(log n) time in the worst case. The BST descent to find the position is O(h), and the rules guarantee h ≤ 2 log₂(n + 1). The fix-up afterwards is also bounded by the height: the recolouring case can move up two levels at a time, at most O(log n) times, and the restructuring cases perform at most two rotations in total. Over a sequence of inserts, the recolouring work is O(1) amortized, so the expensive part is the search itself.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Cost Breakdown
Phase
Work
Bound
Find the position (BST descent)
One comparison per level
O(log n), since height ≤ 2 log₂(n + 1)
Attach a red leaf
Pointer updates
O(1)
Fix-up, case 1 (red uncle)
Recolour three nodes, jump two levels up
O(log n) worst case, O(1) amortized
Fix-up, cases 2 and 3
One or two rotations, then stop
O(1), at most 2 rotations
Colour the root black
Constant
O(1)
Total
O(log n) worst case
Why the Height Bound Holds
Every root-to-leaf path has the same number of black nodes b, and red nodes cannot be adjacent, so no path is longer than 2b. A subtree with black height b has at least 2^b − 1 nodes, which gives b ≤ log₂(n + 1) and h ≤ 2 log₂(n + 1). For a million keys that is at most about 40 levels; in practice it is closer to 20.
Measuring It
The code inserts 10,000 keys in sorted and in shuffled order, counting rotations and measuring the final height.
from __future__ import annotations
from dataclasses import dataclass
RED, BLACK = "R", "B"
@dataclass(eq=False)
class Node:
key: int
color: str = RED
left: Node | None = None
right: Node | None = None
parent: Node | None = None
class RedBlackTree:
"""Red-black tree insert with the standard fix-up (no duplicates)."""
def __init__(self) -> None:
self.root: Node | None = None
self.rotations = 0
def _rotate_left(self, x: Node) -> None:
y = x.right
x.right = y.left
if y.left:
y.left.parent = x
y.parent = x.parent
if x.parent is None:
self.root = y
elif x is x.parent.left:
x.parent.left = y
else:
x.parent.right = y
y.left, x.parent = x, y
self.rotations += 1
def _rotate_right(self, y: Node) -> None:
x = y.left
y.left = x.right
if x.right:
x.right.parent = y
x.parent = y.parent
if y.parent is None:
self.root = x
elif y is y.parent.right:
y.parent.right = x
else:
y.parent.left = x
x.right, y.parent = y, x
self.rotations += 1
def insert(self, key: int) -> None:
parent, node = None, self.root
while node:
if key == node.key:
return
parent, node = node, (node.left if key < node.key else node.right)
new = Node(key, parent=parent)
if parent is None:
self.root = new
elif key < parent.key:
parent.left = new
else:
parent.right = new
self._fix_insert(new)
def _fix_insert(self, node: Node) -> None:
while node.parent and node.parent.color == RED:
parent, grandparent = node.parent, node.parent.parent
if parent is grandparent.left:
uncle = grandparent.right
if uncle and uncle.color == RED: # case 1: recolour, move up
parent.color = uncle.color = BLACK
grandparent.color = RED
node = grandparent
else:
if node is parent.right: # case 2: rotate into a line
node = parent
self._rotate_left(node)
parent = node.parent
parent.color, grandparent.color = BLACK, RED # case 3
self._rotate_right(grandparent)
else:
uncle = grandparent.left
if uncle and uncle.color == RED:
parent.color = uncle.color = BLACK
grandparent.color = RED
node = grandparent
else:
if node is parent.left:
node = parent
self._rotate_right(node)
parent = node.parent
parent.color, grandparent.color = BLACK, RED
self._rotate_left(grandparent)
self.root.color = BLACK
def height(node: Node | None) -> int:
best, stack = -1, [(node, 0)] if node else []
while stack:
current, depth = stack.pop()
best = max(best, depth)
stack.extend((child, depth + 1) for child in (current.left, current.right) if child)
return best
import random
for name, keys in [("sorted", list(range(10_000))),
("shuffled", random.Random(5).sample(range(10_000), 10_000))]:
tree = RedBlackTree()
for key in keys:
tree.insert(key)
print(name, tree.rotations, height(tree.root))
# sorted 9976 23
# shuffled 5912 15
Input
Rotations for 10,000 inserts
Per insert
Final height
Sorted
9,976
about 1
23 (bound: 2 log₂ 10,001 ≈ 26.6)
Shuffled
5,912
about 0.6
15
Sorted input, the worst case for a plain BST (height 9,999), stays logarithmic here, and no insert ever needed more than two rotations.
Comparison
Structure
Insert worst case
Insert average
Rotations per insert
Plain BST
O(n)
O(log n) for random order
0
Red-black tree
O(log n)
O(log n)
≤ 2
AVL tree
O(log n)
O(log n)
≤ 2 (one single or double rotation)
Skip list
O(n) worst, O(log n) expected
O(log n)
n/a
Hash table
O(n) worst, O(1) average
O(1)
n/a, but no ordering
Edge Cases
First insert: O(1); the node becomes a black root.
Parent already black: no fix-up; cost is just the descent.
Duplicate key: this implementation returns after the descent.
Many inserts at the maximum end (timestamps, IDs): still O(log n) each, unlike a plain BST.
Interview Tips
Give the three parts: O(log n) descent, O(log n) worst-case recolouring (O(1) amortized), and at most two rotations.
Connect it to the height bound 2 log₂(n + 1) and explain where it comes from.
A common follow-up: “why do libraries prefer red-black trees over AVL?” Bounded, small restructuring on both insert and delete makes updates cheaper.
40
Compare Red-Black Trees and AVL trees.
KnownRevise
Both are self-balancing binary search trees with O(log n) worst-case search, insert and delete. AVL trees enforce a stricter balance (subtree heights differ by at most 1), so they are shallower and slightly faster for lookups, but they may rotate more on updates, especially deletes. Red-black trees allow looser balance (height up to twice the minimum path), so lookups can be a little deeper, but updates need few, bounded rotations. That is why general-purpose library maps usually use red-black trees, while read-heavy structures can favour AVL.
Read full answerHide full answer
Applies tolanguage-independent (C++ `std::map`, Java `TreeMap`, Linux `rbtree`)
Comparison
Aspect
AVL tree
Red-black tree
Balance rule
Height difference ≤ 1 at every node
Colour rules: no red-red; equal black height on all paths
Height bound
≈ 1.44 log₂(n + 2)
≤ 2 log₂(n + 1)
Search
Slightly faster (shallower)
Slightly slower
Rotations per insert
At most one single or double rotation
At most 2
Rotations per delete
Up to O(log n)
At most 3
Other fix-up work
Update heights on the path, O(log n)
Recolouring, O(log n) worst case, O(1) amortized
Per-node metadata
Height or balance factor (2 bits are enough for the factor)
One colour bit
Implementation
Simpler to reason about; four rotation cases
Delete has more cases; often taken from a library
Typical use
Read-mostly in-memory indexes, lookup tables
Standard library ordered maps and sets, schedulers, kernel data structures
Height in Numbers
For one million keys:
Tree
Minimum possible height
Worst-case height
Perfectly balanced
19
19
AVL
19
about 28
Red-black
19
about 39
Typical heights for random or sorted inputs are much closer to the minimum than these bounds for both trees. The practical lookup difference is a few extra comparisons, which matters only in very lookup-heavy workloads.
Update Behaviour
Insert: both do a constant number of rotations. AVL may update heights all the way up the path; red-black may recolour up the path.
Delete: AVL can rotate at several levels, one per ancestor, up to O(log n) rotations. Red-black needs at most three, which also limits how many nodes are modified, an advantage for concurrent or persistent variants where each modified node must be locked or copied.
Choosing
Workload
Choose
Many lookups, few updates
AVL
Frequent inserts and deletes
Red-black
You want a library, not your own code
Whatever the language provides (usually red-black)
Data on disk or SSD
Neither; use a B+ tree
Simple code, good expected performance
Treap or skip list
Only exact-key lookups
Hash table
Common Misconceptions
“AVL is always faster”: only for lookups, and only by a small constant factor; update-heavy workloads often favour red-black.
“Red-black trees are less balanced, so they can be O(n)”: no, the height is still at most 2 log₂(n + 1).
“Rotations are expensive”: each is O(1) pointer work; the real costs are cache misses and, in concurrent trees, the number of nodes touched.
Interview Tips
Lead with “both O(log n); AVL is stricter, so faster lookups and more rotations; red-black is looser, so cheaper updates”.
Quote the height bounds 1.44 log n versus 2 log n.
Common follow-ups: which one Java and C++ use (red-black), and how a red-black tree relates to a 2-3-4 tree.
A frequent mistake is claiming AVL inserts can need O(log n) rotations; one single or double rotation always suffices for an insert, while deletes can need several.
41
Explain how a Splay Tree works and where it is used.
KnownRevise
A splay tree is a self-adjusting binary search tree that stores no balance information. Every access (search, insert or delete) splays the accessed node to the root with a sequence of rotations (zig, zig-zig and zig-zag steps). Frequently or recently used keys therefore stay near the top. A single operation can cost O(n), but any sequence of m operations costs O(m log n), so each is O(log n) amortized. Splay trees are used where access patterns have locality: caches, some memory allocators and network routing tables, and as a building block in link-cut trees.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Splay Steps (Bottom-Up View)
Let x be the accessed node, p its parent, g its grandparent.
Step
Shape
Rotations
Zig
p is the root
One rotation at p
Zig-zig
x and p are both left children (or both right)
Rotate at g, then at p
Zig-zag
x is a right child of a left child (or the mirror)
Rotate at p, then at g
The zig-zig order (grandparent first) is what makes splaying roughly halve the depth of every node on the access path. Rotating only at the parent repeatedly (“move to root”) does not give the amortized bound.
Code Example
The implementation below uses top-down splaying, which performs the same restructuring during a single descent, building a left tree and a right tree and reassembling them at the end. It needs no parent pointers or recursion.
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def splay(root: Node | None, key: int) -> Node | None:
"""Top-down splay: bring key (or the last node on its search path) to the root."""
if root is None:
return None
header = Node(0) # collects the left and right trees during the descent
left_max = right_min = header
node = root
while True:
if key < node.key:
if node.left is None:
break
if key < node.left.key: # zig-zig: rotate right first
child = node.left
node.left, child.right = child.right, node
node = child
if node.left is None:
break
right_min.left = node # link node into the right tree
right_min = node
node = node.left
elif key > node.key:
if node.right is None:
break
if key > node.right.key: # zag-zag: rotate left first
child = node.right
node.right, child.left = child.left, node
node = child
if node.right is None:
break
left_max.right = node # link node into the left tree
left_max = node
node = node.right
else:
break
left_max.right, right_min.left = node.left, node.right # reassemble
node.left, node.right = header.right, header.left
return node
def insert(root: Node | None, key: int) -> Node:
if root is None:
return Node(key)
root = splay(root, key)
if key == root.key:
return root
new = Node(key)
if key < root.key:
new.left, new.right, root.left = root.left, root, None
else:
new.right, new.left, root.right = root.right, root, None
return new
def contains(root: Node | None, key: int) -> tuple[Node | None, bool]:
"""Search and splay; returns the new root and whether key was found."""
root = splay(root, key)
return root, root is not None and root.key == key
def depth_of(root: Node | None, key: int) -> int:
depth, node = 0, root
while node and node.key != key:
node = node.left if key < node.key else node.right
depth += 1
return depth
root = None
for key in range(1, 11):
root = insert(root, key) # each insert splays the new key to the root
print(root.key, depth_of(root, 1)) # 10 9
root, found = contains(root, 1)
print(found, root.key, depth_of(root, 10)) # True 1 2
root, found = contains(root, 42)
print(found, root.key) # False 10
Walkthrough
Inserting 1 to 10 in order leaves 10 at the root and 1 at depth 9: a chain, because each insert splays the new maximum to the top.
Accessing 1 (the deepest node) costs 9 steps once, but the splay rebuilds the path so that 10 drops to depth 2 and the whole tree becomes much shallower. Later accesses near that path are cheap.
Searching for a missing key (42) splays the last node on the search path, here 10, to the root.
Complexity
Measure
Bound
Single operation, worst case
O(n)
Amortized per operation
O(log n)
Sequence of m operations on n keys
O((m + n) log n)
Space
O(n) nodes; O(1) extra for top-down splaying
Splay trees also have stronger properties: the working-set property (accessing a key used recently is cheap) and static optimality (as good as the best fixed BST for any access frequencies, up to a constant factor).
Where It Is Used
Use
Why splaying helps
Caches and recently used lists
Hot keys stay near the root
Memory allocators, some file systems
Free blocks or recently touched entries accessed repeatedly
Link-cut trees (dynamic connectivity, network flow)
Splay trees represent preferred paths
Trade-offs
Benefit
Cost
No per-node balance data
Individual operations can be O(n): bad for real-time latency
Adapts to access patterns
Reads modify the tree: unsafe for concurrent readers without locking
Simple split and join
Worse than AVL/red-black for uniformly random access due to extra rotations
Good cache behaviour for hot keys
Amortized bounds are harder to explain to stakeholders than worst-case ones
Interview Tips
Say “self-adjusting, no balance data, splay to root on every access, O(log n) amortized”.
Explain why zig-zig rotates the grandparent first.
Expect “when would you not use it?”: concurrent read-heavy workloads and systems needing worst-case latency guarantees.
42
What are Scapegoat Trees, and how do they ensure balance?
KnownRevise
A scapegoat tree is a self-balancing binary search tree that stores no per-node balance data (no heights, colours or priorities). It keeps the tree’s height at most log_{1/α} n for a chosen constant α between 0.5 and 1 (commonly 2/3). When an insert makes a node too deep, the algorithm walks back up to find a scapegoat: an ancestor whose subtree is not α-weight-balanced (one child holds more than α of its nodes). That whole subtree is then rebuilt into a perfectly balanced one. Updates cost O(log n) amortized, and searches are O(log n) worst case.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
The Balance Rule
A node v is α-weight-balanced if size(child) ≤ α · size(v) for both children. If every node were α-weight-balanced, the height would be at most log_{1/α} n. Scapegoat trees do not enforce this at every node; they only react when a new node lands deeper than log_{1/α} n, which guarantees that some ancestor on its path violates the rule.
α
Height limit (≈)
Rebuild frequency
0.55
1.16 log₂ n
Frequent (strict balance, more rebuilding)
2/3
1.71 log₂ n
Moderate (common choice)
0.8
3.1 log₂ n
Rare (cheaper inserts, deeper tree)
Insert Algorithm
Insert as in a plain BST, recording the path.
If the new node’s depth exceeds ⌊log_{1/α} n⌋, walk up the path computing subtree sizes.
The first ancestor where a child’s size exceeds α × the ancestor’s size is the scapegoat.
Flatten the scapegoat’s subtree in order (O(k) for k nodes) and rebuild it perfectly balanced by picking middle elements as roots.
Code Example
from __future__ import annotations
import math
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def size(node: Node | None) -> int:
"""Subtree size by iterative traversal (scapegoat trees store no per-node data)."""
count, stack = 0, [node] if node else []
while stack:
current = stack.pop()
count += 1
stack.extend(child for child in (current.left, current.right) if child)
return count
def flatten(node: Node | None) -> list[Node]:
result, stack = [], []
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node)
node = node.right
return result
def build_balanced(nodes: list[Node], low: int, high: int) -> Node | None:
"""Rebuild a perfectly balanced subtree from sorted nodes[low:high]."""
if low >= high:
return None
middle = (low + high) // 2
root = nodes[middle]
root.left = build_balanced(nodes, low, middle)
root.right = build_balanced(nodes, middle + 1, high)
return root
class ScapegoatTree:
def __init__(self, alpha: float = 2 / 3) -> None:
self.root: Node | None = None
self.alpha = alpha
self.count = 0
self.rebuilds = 0
def _depth_limit(self) -> int:
return math.floor(math.log(self.count, 1 / self.alpha)) if self.count > 1 else 1
def insert(self, key: int) -> None:
path: list[Node] = []
node = self.root
while node:
if key == node.key:
return
path.append(node)
node = node.left if key < node.key else node.right
new = Node(key)
self.count += 1
if not path:
self.root = new
return
parent = path[-1]
if key < parent.key:
parent.left = new
else:
parent.right = new
if len(path) <= self._depth_limit():
return
# Too deep: walk up to find the scapegoat, an ancestor that is not alpha-weight-balanced.
child, child_size = new, 1
for i in range(len(path) - 1, -1, -1):
ancestor = path[i]
sibling = ancestor.right if ancestor.left is child else ancestor.left
ancestor_size = child_size + size(sibling) + 1
if child_size > self.alpha * ancestor_size:
nodes = flatten(ancestor)
rebuilt = build_balanced(nodes, 0, len(nodes))
if i == 0:
self.root = rebuilt
elif path[i - 1].left is ancestor:
path[i - 1].left = rebuilt
else:
path[i - 1].right = rebuilt
self.rebuilds += 1
return
child, child_size = ancestor, ancestor_size
def height(node: Node | None) -> int:
best, stack = -1, [(node, 0)] if node else []
while stack:
current, depth = stack.pop()
best = max(best, depth)
stack.extend((child, depth + 1) for child in (current.left, current.right) if child)
return best
tree = ScapegoatTree()
for key in range(1, 1025): # sorted input
tree.insert(key)
print(height(tree.root), tree.rebuilds) # 17 384
print(height(tree.root) <= math.log(1024, 1.5)) # True
Walkthrough
With sorted keys 1 to 1,024 (the worst case for a plain BST), each time the rightmost path grows too deep, the scapegoat subtree is rebuilt. The run above performs 384 rebuilds, mostly small ones, and ends with height 17, within the log₁.₅ 1024 ≈ 17.1 limit. A plain BST would have height 1,023.
Complexity
Operation
Bound
Why
Search
O(log n) worst case
Height ≤ log_{1/α} n
Insert
O(log n) amortized; one insert can cost O(n)
A rebuild of k nodes is paid for by the Ω(k) inserts that unbalanced that subtree
Delete
O(log n) amortized
Plain BST delete; rebuild the whole tree once the count falls below α × the largest count since the last rebuild
Space
O(n) nodes and no per-node balance fields; O(log n) for the path; the rebuild uses an O(k) list
Trade-offs
Benefit
Cost
No extra fields per node: smaller nodes
Occasional O(n) pauses during rebuilds
Simple code: plain BST plus “rebuild subtree”
Amortized, not worst-case, update time
α tunes the speed/height trade-off
Less common in libraries
Interview Tips
Explain the idea in one line: “when a path gets too deep, find the unbalanced ancestor and rebuild its subtree perfectly”.
Mention no per-node metadata and amortized updates as the key contrast with AVL and red-black trees.
A follow-up might ask about α: smaller means shallower trees but more rebuilding.
43
Discuss the concept of a Treap and its expected time complexities.
KnownRevise
A treap (tree + heap) is a binary search tree in which every node also has a random priority. Keys follow BST order (left < node < right) and priorities follow heap order (a parent’s priority is higher than its children’s). Because priorities are random, the shape is the same as a BST built by inserting the keys in a random order, whatever order they really arrive in. That gives O(log n) expected time for search, insert and delete, with simple code and no balance rules to maintain.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Why Random Priorities Balance the Tree
For a given set of keys and priorities, exactly one tree satisfies both orders: the key with the highest priority is the root, and the rest split into left and right subtrees by key. A random priority is equivalent to a random insertion time, and random BSTs have expected depth about 2 ln n ≈ 1.39 log₂ n. An adversary who does not know the priorities cannot force a bad shape.
Operations
Operation
Method
Expected time
Search
Plain BST search
O(log n)
Insert
BST insert, then rotate the new node up while its priority beats its parent’s; or split + merge
O(log n)
Delete
Rotate the node down until it is a leaf and remove it; or two splits + merge
O(log n)
Split by key
Divide into keys < k and ≥ k
O(log n)
Merge
Join two treaps where all keys of one are smaller
O(log n)
Union / intersection of treaps of sizes m ≤ n
Recursive split and merge
O(m log(n/m + 1)) expected
Split and merge make treaps convenient for ordered sets that are cut and joined often, and for implicit treaps (keyed by position), which support insert, delete and reverse on sequences in O(log n).
Code Example
from __future__ import annotations
import random
from dataclasses import dataclass, field
_rng = random.Random(2024)
@dataclass
class Node:
key: int
priority: float = field(default_factory=_rng.random)
left: Node | None = None
right: Node | None = None
def split(node: Node | None, key: int) -> tuple[Node | None, Node | None]:
"""Split into (keys < key, keys >= key)."""
if node is None:
return None, None
if node.key < key:
node.right, right = split(node.right, key)
return node, right
left, node.left = split(node.left, key)
return left, node
def merge(left: Node | None, right: Node | None) -> Node | None:
"""Merge two treaps where every key in left is smaller than every key in right."""
if left is None or right is None:
return left or right
if left.priority > right.priority:
left.right = merge(left.right, right)
return left
right.left = merge(left, right.left)
return right
def contains(node: Node | None, key: int) -> bool:
while node and node.key != key:
node = node.left if key < node.key else node.right
return node is not None
def insert(root: Node | None, key: int) -> Node | None:
if contains(root, key):
return root
smaller, larger = split(root, key)
return merge(merge(smaller, Node(key)), larger)
def delete(root: Node | None, key: int) -> Node | None:
smaller, rest = split(root, key)
_, larger = split(rest, key + 1) # drop the node equal to key (integer keys)
return merge(smaller, larger)
def height(node: Node | None) -> int:
best, stack = -1, [(node, 0)] if node else []
while stack:
current, depth = stack.pop()
best = max(best, depth)
stack.extend((child, depth + 1) for child in (current.left, current.right) if child)
return best
def inorder(node: Node | None) -> list[int]:
result, stack = [], []
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
result.append(node.key)
node = node.right
return result
root = None
for key in range(1, 10_001): # sorted input, the worst case for a plain BST
root = insert(root, key)
print(height(root)) # 29
root = delete(root, 5000)
print(contains(root, 5000), contains(root, 5001), len(inorder(root))) # False True 9999
split and merge recurse only as deep as the tree height, which is O(log n) expected (29 here for 10,000 keys), so Python’s recursion limit is not a concern.
Walkthrough: Insert via Split and Merge
To insert key 5 into a treap holding {2, 4, 7, 9}:
split(root, 5) gives A = {2, 4} and B = {7, 9}, each still a valid treap.
merge(A, Node(5)): the new node joins on the right side of A, rising above nodes whose priority is lower.
merge(result, B) joins the rest; at each step the higher-priority root stays on top.
Complexity
Measure
Bound
Expected height
O(log n), about 1.39 log₂ n for average depth
Search, insert, delete, split, merge
O(log n) expected
Worst case (astronomically unlikely with good randomness)
O(n)
Expected rotations per insert or delete
O(1) (fewer than 2 on average)
Space
O(n) nodes plus one priority per node
With 10,000 sorted inserts, the example tree’s height is 29, while a plain BST would have height 9,999.
Edge Cases
Duplicates: this version ignores them; store a count for a multiset.
Equal priorities: practically impossible with floats; ties can be broken by key.
Deterministic seeds: good for tests; in production use unpredictable randomness if input could be adversarial.
Delete of a missing key: the splits leave the tree unchanged.
Interview Tips
Define it as “BST by key, heap by random priority” and explain why that equals a random insertion order.
Say expected O(log n), not worst case, and contrast with red-black and AVL trees.
A common follow-up: “how do you reverse a subarray in O(log n)?”, answered with an implicit treap and a lazy reverse flag.
44
What is the difference between a Heap and a Red-Black Tree?
KnownRevise
A heap is a priority queue: it keeps only a partial order (each parent is smaller than its children in a min-heap), which is enough to return the minimum in O(1) and insert or remove it in O(log n), usually stored compactly in an array. A red-black tree is a balanced binary search tree: it keeps a total order (left < node < right), so it supports search, delete of any key, predecessor/successor, max and min, and sorted iteration, all in O(log n). Use a heap when you only need the smallest (or largest) item next; use a red-black tree when you need ordered lookups.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Binary heap
Red-black tree
Ordering
Heap order: parent ≤ children
BST order: left < node < right
Shape
Complete binary tree
Balanced BST (height ≤ 2 log₂(n + 1))
Storage
Array, no pointers
Nodes with left, right, parent pointers and a colour
Find min (min-heap)
O(1)
O(log n), or O(1) with a cached pointer
Find max (min-heap)
O(n)
O(log n)
Insert
O(log n); O(1) average for random input
O(log n)
Remove min
O(log n)
O(log n)
Search an arbitrary key
O(n)
O(log n)
Delete an arbitrary key
O(n) to find it, O(log n) to fix
O(log n)
Predecessor, successor, range query
Not supported
O(log n), plus O(k) results
Sorted iteration
O(n log n) (pop everything)
O(n) in-order
Build from n items
O(n) (heapify)
O(n log n)
Memory and cache behaviour
Compact and cache-friendly
Higher overhead, scattered nodes
Duplicates
Natural
Need a policy
Library examples
Python heapq, Java PriorityQueue, C++ std::priority_queue
C++ std::map and std::set, Java TreeMap and TreeSet
Code Example
Python has no built-in red-black tree, so a sorted list with bisect stands in for its ordered view (with O(n) inserts, unlike a real tree).
import heapq
from bisect import bisect_left, insort
deadlines = [30, 10, 50, 20, 40]
heap: list[int] = []
for deadline in deadlines:
heapq.heappush(heap, deadline) # O(log n)
print(heap[0]) # 10 (minimum in O(1))
print(heap) # [10, 20, 50, 30, 40] (not sorted)
print(40 in heap) # True, but this is an O(n) scan
ordered: list[int] = [] # stand-in for a balanced BST's ordered view
for deadline in deadlines:
insort(ordered, deadline)
print(ordered) # [10, 20, 30, 40, 50]
print(ordered[bisect_left(ordered, 25)]) # 30 (ceiling of 25)
print(ordered[-1]) # 50 (maximum; a min-heap would need O(n))
The heap’s array [10, 20, 50, 30, 40] is not sorted: only heap[0] is guaranteed to be the minimum. The ordered structure answers “smallest deadline ≥ 25” and “largest deadline” directly.
Ordered map, leaderboard with rank queries, interval booking, “next key after x”
Red-black tree (or another balanced BST)
Both min and max often
Two heaps with lazy deletion, a min-max heap, or a balanced BST
Median of a stream
Two heaps (max-heap for the lower half, min-heap for the upper half)
Priority queue with arbitrary updates (decrease-key)
Heap with an index map, or a balanced BST keyed by (priority, id)
Complexity of the Example
Each heappush is O(log n); reading heap[0] is O(1); the in test is an O(n) scan. Each insort is O(log n) to find the position but O(n) to shift elements; a red-black tree would make that insert O(log n). The bisect_left lookup is O(log n).
Max-heap in Python:heapq is a min-heap; push negated keys or (−priority, item) tuples.
Ties: heaps return equal priorities in arbitrary order; add a counter to tuples for stable ordering.
Interview Tips
Say “partial order for fast min versus total order for search and range”.
The classic follow-up: “why not use a red-black tree as a priority queue?” It works (O(log n) for everything), but a heap is simpler, more compact and builds in O(n).
A frequent mistake is assuming a heap’s array is sorted or that a heap can search in O(log n).
45
What is a B-Tree?
KnownRevise
A B-tree is a self-balancing search tree in which each node holds many sorted keys and has many children, and all leaves are at the same depth. With minimum degree t, every node except the root holds between t − 1 and 2t − 1 keys, and an internal node with k keys has k + 1 children. Because each node is sized to fit a disk page (often hundreds of keys), the tree is very shallow, so a lookup reads only a few pages. B-trees and their B+ tree variant are the standard index structure in databases and file systems.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Keys in the child between keys a and b lie strictly between a and b.
Every leaf is at the same depth: the tree grows and shrinks at the root.
Rules (Minimum Degree t ≥ 2)
Rule
Value
Keys per non-root node
t − 1 to 2t − 1
Children per internal non-root node
t to 2t
Root
At least 1 key (if the tree is not empty)
Height for n keys
at most log_t((n + 1) / 2)
With t = 2, nodes hold 1 to 3 keys: a 2-3-4 tree.
Operations
Operation
How
Time
Search
Binary search inside the node, then descend to one child
O(log n) comparisons; O(log_t n) node reads
Insert
Descend to a leaf, splitting any full node on the way (its median moves up); insert into the leaf
O(t · log_t n)
Delete
Remove from a leaf, or swap with predecessor or successor; borrow from a sibling or merge nodes to keep at least t − 1 keys
O(t · log_t n)
Range scan
In-order walk (B+ trees make this faster with linked leaves)
O(log_t n + k)
Code Example
from __future__ import annotations
from bisect import bisect_left
from dataclasses import dataclass, field
@dataclass
class BNode:
keys: list[int] = field(default_factory=list)
children: list[BNode] = field(default_factory=list)
@property
def is_leaf(self) -> bool:
return not self.children
class BTree:
"""B-tree of minimum degree t: every node except the root holds t-1 to 2t-1 keys."""
def __init__(self, t: int = 3) -> None:
if t < 2:
raise ValueError("minimum degree must be at least 2")
self.t = t
self.root = BNode()
def search(self, key: int) -> bool:
node = self.root
while True:
i = bisect_left(node.keys, key) # binary search inside the node
if i < len(node.keys) and node.keys[i] == key:
return True
if node.is_leaf:
return False
node = node.children[i]
def _split_child(self, parent: BNode, i: int) -> None:
"""Split parent's full child i around its median key."""
t, full = self.t, parent.children[i]
right = BNode(full.keys[t:], full.children[t:])
median = full.keys[t - 1]
full.keys, full.children = full.keys[:t - 1], full.children[:t]
parent.keys.insert(i, median)
parent.children.insert(i + 1, right)
def insert(self, key: int) -> None:
if self.search(key):
return
if len(self.root.keys) == 2 * self.t - 1: # full root: the tree grows upward
new_root = BNode(children=[self.root])
self._split_child(new_root, 0)
self.root = new_root
node = self.root
while not node.is_leaf: # split full children on the way down
i = bisect_left(node.keys, key)
if len(node.children[i].keys) == 2 * self.t - 1:
self._split_child(node, i)
if key > node.keys[i]:
i += 1
node = node.children[i]
node.keys.insert(bisect_left(node.keys, key), key)
def height(self) -> int:
height, node = 0, self.root
while not node.is_leaf:
node = node.children[0]
height += 1
return height
tree = BTree(t=2) # a 2-3-4 tree: 1 to 3 keys per node
for key in [10, 20, 5, 6, 12, 30, 7, 17]:
tree.insert(key)
print(tree.root.keys, [child.keys for child in tree.root.children]) # [10, 20] [[5, 6, 7], [12, 17], [30]]
print(tree.search(6), tree.search(15)) # True False
big = BTree(t=50) # up to 99 keys per node
for key in range(100_000):
big.insert(key)
print(big.height()) # 2
The splitting-on-the-way-down approach guarantees the parent always has room for a median, so insertion needs only one pass from the root. With up to 99 keys per node, 100,000 keys fit in a tree of height 2 (three levels).
Walkthrough (t = 2)
Insert
Effect
10, 20, 5
Root [5, 10, 20] is now full
6
Root is full: split, median 10 moves up: [10] over [5] and [20]; 6 goes into [5, 6]
12, 30
[12, 20, 30]
7
[5, 6, 7]
17
Child [12, 20, 30] is full: split, 20 moves up: root [10, 20]; 17 goes into [12, 17]
Final: root [10, 20], leaves [5, 6, 7], [12, 17], [30], all at depth 1.
Complexity
Search: O(log_t n) node visits, each with an O(log t) binary search: O(log n) comparisons overall.
Insert/Delete: O(log_t n) node visits; a split or merge copies O(t) keys.
Space: O(n); nodes are at least about half full.
Edge Cases
Empty tree: the root is an empty leaf; search returns False.
Duplicates: ignored here; databases use (key, row id) pairs to make index entries unique.
Sorted inserts: nodes on the right edge split repeatedly, leaving left nodes half full; some databases optimise splits for this case.
t < 2: invalid.
Interview Tips
Lead with “many keys per node, all leaves at the same depth, designed for disk pages”.
Explain split (median moves up, the tree grows at the root) clearly.
Expect a follow-up on B-tree versus B+ tree (B+ trees keep data only in leaves and link the leaves for range scans).
46
How is an AVL Tree different from a B-Tree?
KnownRevise
An AVL tree is a binary search tree (one key and two children per node) that stays balanced by keeping subtree heights within 1 of each other, using rotations. A B-tree is a multi-way search tree (many keys and children per node) that keeps all leaves at the same depth by splitting and merging nodes. AVL trees are designed for in-memory data, where each node access is cheap; B-trees are designed for disk and SSD storage (and cache-conscious memory structures), where reading a node costs a page I/O and few, large nodes are much faster than many small ones.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
AVL tree
B-tree
Keys per node
1
Between t − 1 and 2t − 1 (often hundreds)
Children per node
≤ 2
Up to 2t
Balance rule
Height difference ≤ 1 at every node
All leaves at the same depth; nodes at least about half full
Restoring balance
Rotations
Splits (insert), borrow or merge (delete)
Where the tree grows
Anywhere; height changes locally
Only at the root
Height for n keys
≤ about 1.44 log₂ n
≤ about log_t n
Search cost
O(log n) node visits
O(log_t n) node visits, O(log n) comparisons in total
Memory overhead
Two pointers plus height per key
Pointers per node, amortised over many keys
Cache and disk friendliness
Poor: one cache miss or page read per level
Good: one page per level, keys contiguous
Typical use
In-memory ordered maps, read-heavy indexes
Database indexes, file systems, key-value stores
The Height Difference in Numbers
import math
def levels_needed(keys: int, fanout: int) -> int:
"""Minimum number of levels for a search tree whose nodes have up to `fanout` children."""
levels, capacity = 0, 0
while capacity < keys:
levels += 1
capacity = fanout ** levels - 1 # keys that fit in a full tree of this many levels
return levels
for keys in (1_000_000, 1_000_000_000):
avl_worst = math.floor(1.44 * math.log2(keys + 2))
print(keys, levels_needed(keys, 2), avl_worst, levels_needed(keys, 500))
# 1000000 20 28 3
# 1000000000 30 43 4
Keys
Perfect binary tree
AVL worst case
B-tree, 500-way
1 million
20 levels
28
3
1 billion
30 levels
43
4
If each level were a disk read of about 100 µs on an SSD (a rough order of magnitude), an AVL lookup over a billion keys could take about 3–4 ms, while a B-tree lookup takes well under a millisecond, and its top levels usually sit in memory anyway.
Why Not Use a B-Tree Everywhere?
In memory, a B-tree’s node search is a scan or binary search over many keys, and splits copy arrays. For small or pointer-friendly data, a red-black or AVL tree is simpler.
In practice, cache-friendly in-memory B-trees often beat binary trees too, because a node spans a few cache lines (Rust’s BTreeMap is a B-tree). The trade-off is implementation complexity.
AVL trees give simple, predictable single-key updates with no array shifting.
Update Behaviour
Event
AVL tree
B-tree
Insert
Leaf added; up to one single or double rotation
Key added to a leaf; full nodes split, possibly up to the root
Delete
Node removed; possibly a rotation at each level
Key removed; nodes that fall below t − 1 keys borrow or merge
Concurrency
Rotations touch a few nodes per level
Latch coupling and page-level locks are well understood in databases
Complexity
Operation
AVL
B-tree (minimum degree t)
Search
O(log n)
O(log_t n) node reads, O(log n) comparisons
Insert / delete
O(log n)
O(t · log_t n) work, O(log_t n) I/Os
Space
O(n)
O(n), nodes at least half full
The level calculation above runs in O(log n) time and O(1) space.
Choosing
Data fits in memory, simple ordered map needed: AVL or red-black (or the language’s built-in ordered map).
Data on disk or SSD, or very large in-memory indexes where cache misses dominate: B-tree / B+ tree.
Need fast range scans over disk data: B+ tree with linked leaves.
Interview Tips
Say “binary and rotation-balanced versus multi-way and split/merge-balanced”, then connect it to I/O cost per level.
Quote the heights (about 30 versus 4 for a billion keys).
A common follow-up: why databases use B+ trees rather than B-trees (data only in leaves, more keys per internal node, linked leaves for range scans).
47
What are the differences between B-Trees and B+ Trees?
KnownRevise
Both are balanced multi-way search trees with all leaves at the same depth. In a B-tree, every node (internal or leaf) stores keys together with their data (or record pointers), and each key appears once. In a B+ tree, internal nodes store only keys used for routing, all data lives in the leaves, and the leaves are linked in key order. That makes B+ trees shallower (more keys fit in each internal node), gives every lookup the same path length, and makes range scans a simple walk along the leaf list, which is why most relational databases and many file systems use B+ trees.
Read full answerHide full answer
Applies todatabase indexes (InnoDB, PostgreSQL, SQL Server), file systems (NTFS, XFS, Btrfs-like designs) and key-value stores
Comparison
Aspect
B-tree
B+ tree
Where data is stored
In every node, next to its key
Only in leaves
Internal nodes
Keys + data + child pointers
Keys + child pointers only
Key duplication
Each key once
Separator keys repeated in internal nodes and leaves
Fanout of internal nodes
Lower (data takes space)
Higher (only keys), so a shallower tree
Search path
Can stop early at an internal node
Always ends at a leaf: predictable cost
Range query BETWEEN a AND b
In-order traversal moving up and down the tree
Find a in a leaf, then follow next-leaf pointers
Full scan in key order
Tree traversal
Walk the leaf linked list
Insert / delete
Split or merge; deleting from an internal node needs a predecessor or successor swap
Always insert and delete at leaves; separators adjust
Typical use
Some file systems and older designs, in-memory variants
Relational database indexes, most file systems and storage engines
Picture
B-tree (data in every node):
[ 30:row30 ]
/ \
[ 10:row10 | 20:row20 ] [ 40:row40 | 50:row50 ]
B+ tree (data only in leaves, leaves linked):
[ 30 ]
/ \
[10:r | 20:r] <-> [30:r | 40:r | 50:r]
In the B+ tree, 30 appears twice: as a separator in the root and as a real entry in a leaf.
Why the Fanout Difference Matters
Suppose a page is 16 KiB, a key is 8 bytes and a child pointer 6 bytes (sizes vary by engine; these are illustrative):
B+ tree internal node: about 16384 / 14 ≈ 1,170 children.
B-tree node with 100-byte rows stored inline: about 16384 / 114 ≈ 140 children.
For 100 million rows, the B+ tree needs about 3 levels; the B-tree about 4. Every extra level is potentially another I/O per lookup.
Range Query Walkthrough
SELECT * FROM orders WHERE id BETWEEN 20 AND 45:
Descend from the root to the leaf containing 20: one page per level.
Read entries ≥ 20 in that leaf.
Follow the next-leaf pointer and keep reading until a key exceeds 45.
A B-tree must instead do an in-order traversal, moving back up to parents and down to the next subtree, which touches more pages and is harder to do with sequential I/O.
Database Details
Clustered index (InnoDB primary key, SQL Server clustered index): B+ tree leaves store the rows themselves, in key order.
Secondary indexes: leaves store the indexed key plus a row identifier or the primary key; a lookup then fetches the row (unless the index covers the query).
Prefix and suffix compression of separator keys further increases fanout.
PostgreSQL stores tables as heaps and uses B+ tree-style indexes (its “btree” access method, based on the Lehman-Yao design with right-links for concurrency).
Complexity (Both, Order m)
Operation
Cost
Point lookup
O(log_m n) page reads
Insert / delete
O(log_m n) page reads and writes; splits or merges occasionally
Range scan of k results
B+ tree: O(log_m n + k/m) pages; B-tree: more pages due to up-and-down traversal
Space
O(n); B+ tree adds duplicated separators, a small cost
Interview Tips
Say “B+ tree: data only in leaves, leaves linked”, then give the two consequences: higher fanout and fast range scans.
Mention clustered versus secondary indexes when the discussion turns to databases.
A common mistake is saying B-trees cannot do range queries; they can, just less efficiently.
48
What is a Segment Tree, and what are its applications?
KnownRevise
A segment tree is a binary tree built over an array in which each node stores an aggregate (sum, minimum, maximum, GCD, count…) of a contiguous range of the array. The root covers the whole array, each child covers half of its parent’s range, and the leaves are single elements. It answers range queries and handles point updates in O(log n) each, compared with O(n) for one or the other using a plain array or prefix sums. With lazy propagation it also supports range updates in O(log n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
When You Need It
Approach
Range query
Point update
Range update
Plain array
O(n)
O(1)
O(n)
Prefix sums
O(1) (sums only)
O(n)
O(n)
Fenwick tree
O(log n) (invertible operations such as sum)
O(log n)
O(log n) with tricks
Segment tree
O(log n) (any associative operation)
O(log n)
O(log n) with lazy propagation
Use a segment tree when both queries and updates are frequent, or when the operation is not invertible (min, max, GCD), which rules out prefix-sum tricks and plain Fenwick trees.
A query on [2, 6) combines [2,4) and [4,6): 14 + 5 = 19. Any range splits into at most about 2 log₂ n such nodes.
Code Example
The iterative (bottom-up) version stores the tree in an array of size 2n: leaves at indexes n … 2n − 1, and node i holds the combination of 2i and 2i + 1.
class SegmentTree:
"""Iterative segment tree for range sums with point updates."""
def __init__(self, values: list[int]) -> None:
self.size = len(values)
self.tree = [0] * (2 * self.size)
self.tree[self.size:] = values # leaves in the second half
for i in range(self.size - 1, 0, -1): # internal node i = sum of 2i and 2i+1
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def update(self, index: int, value: int) -> None:
"""Set values[index] = value in O(log n)."""
i = index + self.size
self.tree[i] = value
while i > 1:
i //= 2
self.tree[i] = self.tree[2 * i] + self.tree[2 * i + 1]
def query(self, left: int, right: int) -> int:
"""Sum of values[left:right] (half-open) in O(log n)."""
total = 0
left += self.size
right += self.size
while left < right:
if left % 2 == 1:
total += self.tree[left]
left += 1
if right % 2 == 1:
right -= 1
total += self.tree[right]
left //= 2
right //= 2
return total
prices = [5, 3, 8, 6, 1, 4, 7, 2]
tree = SegmentTree(prices)
print(tree.query(2, 6)) # 19 (8 + 6 + 1 + 4)
tree.update(4, 10) # prices[4] = 10
print(tree.query(2, 6)) # 28
print(tree.query(0, 8)) # 45
Walkthrough: query(2, 6) with n = 8
Step
left, right (array indexes)
Action
Total
Start
10, 14
0
Level 0
both even
move up: 5, 7
0
Level 1
left = 5 odd: add tree[5] = 14 (range [2,4)); right = 7 odd: add tree[6] = 5 (range [4,6))
19
Level 2
3, 3
loop ends
19
Complexity
Operation
Time
Space
Build
O(n)
O(n) (2n entries here; recursive versions often use 4n)
Point update
O(log n)
O(1) extra
Range query
O(log n)
O(1) extra
Range update with lazy propagation
O(log n)
O(n) for lazy tags
The iterative version uses no recursion, so it has no depth concerns.
Applications
Area
Example
Competitive programming and interviews
Range sum or min queries with updates, counting inversions
Analytics and dashboards
Rolling aggregates over time buckets that receive late updates
Computational geometry
Rectangle union area and sweep-line algorithms (segment trees over coordinates)
Scheduling and booking
“Is any slot in this range free?” with range assignments (lazy propagation)
Games and simulations
Range damage and health queries
Databases and time series
Min or max over windows with updates
Edge Cases
Empty array:size = 0; queries return 0 (guard if needed).
Non-power-of-two sizes: the iterative layout handles any n.
Non-commutative operations (such as matrix products): combine left and right results separately in the query.
Different identity values: use float("inf") for min, -inf for max, 0 for sum and GCD.
Interview Tips
Explain “each node stores the answer for its range; a query combines O(log n) nodes”.
Know when a Fenwick tree is enough (prefix-invertible operations like sums) and when you need a segment tree (min, max, range assignment).
A common follow-up is lazy propagation for range updates.
49
Explain Trie (Prefix Trees) and their common use-cases.
KnownRevise
A trie (prefix tree) stores strings character by character along paths from the root: each edge is labelled with a character, each node represents the prefix spelled by the path to it, and a flag marks nodes where a complete word ends. Words that share a prefix share the same nodes, so lookup, insert and prefix checks take O(L) time for a string of length L, independent of how many words are stored. That makes tries the natural structure for autocomplete, spell checking and prefix matching.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Structure
(root)
/ \
c d
| |
a o
/ \ \
r* t* g*
/ | \
d* e* t*
Words: car, card, care, cart, cat, dog (* marks the end of a word). The prefix ca is stored once for five words.
Code Example
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class TrieNode:
children: dict[str, TrieNode] = field(default_factory=dict)
is_word: bool = False
class Trie:
def __init__(self) -> None:
self.root = TrieNode()
def insert(self, word: str) -> None:
node = self.root
for character in word:
node = node.children.setdefault(character, TrieNode())
node.is_word = True
def _walk(self, prefix: str) -> TrieNode | None:
node = self.root
for character in prefix:
node = node.children.get(character)
if node is None:
return None
return node
def contains(self, word: str) -> bool:
node = self._walk(word)
return node is not None and node.is_word
def words_with_prefix(self, prefix: str, limit: int = 10) -> list[str]:
"""Autocomplete: up to `limit` words starting with prefix, in sorted order."""
start = self._walk(prefix)
results: list[str] = []
stack = [(start, prefix)] if start else []
while stack and len(results) < limit:
node, text = stack.pop()
if node.is_word:
results.append(text)
for character in sorted(node.children, reverse=True):
stack.append((node.children[character], text + character))
return results
trie = Trie()
for word in ["car", "card", "care", "cart", "cat", "dog"]:
trie.insert(word)
print(trie.contains("car"), trie.contains("ca")) # True False
print(trie.words_with_prefix("car")) # ['car', 'card', 'care', 'cart']
print(trie.words_with_prefix("x")) # []
Walkthrough: words_with_prefix("car")
Walk c → a → r from the root: 3 steps.
DFS below that node, visiting children in alphabetical order: car (the node itself is a word), then card, care, cart.
Stop when limit results are collected.
Complexity
Operation
Time
Notes
Insert word of length L
O(L)
One node per new character
Exact lookup
O(L)
Independent of the number of stored words
Prefix check
O(P)
P = prefix length
Autocomplete with k results
O(P + size of explored subtree)
Bounded by limit
Space
O(total characters) in the worst case
Each node holds a children map; shared prefixes save space
Dictionary-based children cost O(1) average per step. Fixed 26-slot arrays give O(1) worst case for lowercase ASCII but waste memory.
Trie versus Other Structures
Need
Trie
Hash set
Balanced BST / sorted list
Exact lookup
O(L)
O(L) to hash, O(1) average
O(L · log n) comparisons
All words with a prefix
O(P + output)
O(n) scan
O(L · log n + output)
Longest common prefix, longest prefix match
Natural
Hard
Possible
Sorted iteration
DFS in character order
No
Yes
Memory
High per node
Lower
Lower
Common Use Cases
Use
How the trie helps
Autocomplete and search suggestions
Walk the prefix, then list the subtree (often with stored popularity counts)
Spell checking and suggestions
Fast membership tests; DFS with edit-distance pruning
IP routing (longest prefix match)
Binary tries over address bits find the most specific route
Word games (Boggle, word search)
Prune grid searches when no word has the current prefix
Dictionaries for tokenizers and keyword matching
Aho-Corasick automaton is built on a trie to match many patterns at once
Phone directories and T9-style input
Prefix lookups on digit sequences
Space-Saving Variants
Radix / Patricia tree: compress chains of single-child nodes into one edge labelled with a string.
Ternary search tree: three pointers per node, less memory than maps of children.
Double-array trie or DAWG (directed acyclic word graph): shares suffixes too, used for large static dictionaries.
Edge Cases
Empty string: marks the root as a word if inserted.
Prefix that is also a word (car and card): handled by the is_word flag, not by being a leaf.
Case and Unicode: normalise (for example lowercase and NFC) before inserting; dict children handle any characters.
Deletion: unset is_word, then prune nodes that have no children and are not words.
Interview Tips
Say “O(L) per operation, independent of the number of words, and prefixes are shared”.
Common problems: implement a trie, word search II, replace words, longest common prefix.
A frequent mistake is treating “is a leaf” as “is a word”; a word can end at an internal node.
50
What is an Interval Tree, and how is it different from a Segment Tree?
KnownRevise
An interval tree stores a dynamic set of intervals and answers “which stored intervals overlap this point or range?” in O(log n) per result found. The common design is a balanced BST keyed by interval start, where each node also stores the maximum end in its subtree, so whole subtrees can be skipped. A segment tree is built over a fixed array of positions and stores an aggregate (sum, min, max) for each range of positions, answering range-aggregate queries with updates. The short version: interval trees store intervals as data; segment trees store values at positions and summarise ranges of them.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Comparison
Aspect
Interval tree
Segment tree
What it stores
A set of intervals (meetings, reservations, genome features)
Values indexed by position in a fixed range
Typical query
All intervals overlapping a point or range
Aggregate over positions [l, r)
Answer
A list of intervals
One value (sum, min, max, count)
Updates
Insert or delete intervals
Point updates, range updates with lazy propagation
Underlying structure
Balanced BST on start, augmented with max end
Complete binary tree over array indexes
Time
O(log n) update; O(min(n, k log n)) to report k overlaps (O(log n + k) for a centred interval tree)
O(log n) update and query
Space
O(n) for n intervals
O(N) for a coordinate range of size N (compress coordinates if large)
Coordinate range
Any; no preprocessing
Must be known up front or compressed
Segment trees can also be used to store intervals for “stabbing” queries (each interval is placed in O(log N) nodes), which is common in computational geometry; that variant needs the coordinates in advance.
How the Augmentation Prunes the Search
Two half-open intervals [a, b) and [c, d) overlap when a < d and c < b. At each node:
If the subtree’s max_end ≤ query start, no interval below can overlap: skip it.
The right subtree only holds intervals starting at or after node.start, so skip it if node.start ≥ query end.
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
start: int
end: int # half-open interval [start, end)
max_end: int = 0 # largest end in this subtree (the augmentation)
left: Node | None = None
right: Node | None = None
def __post_init__(self) -> None:
self.max_end = self.end
class IntervalTree:
"""BST keyed by interval start, augmented with the maximum end below each node."""
def __init__(self) -> None:
self.root: Node | None = None
def insert(self, start: int, end: int) -> None:
if start >= end:
raise ValueError("empty interval")
new = Node(start, end)
if self.root is None:
self.root = new
return
node = self.root
while True:
node.max_end = max(node.max_end, end) # keep the augmentation correct
side = "left" if start < node.start else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, new)
return
node = child
def overlapping(self, start: int, end: int) -> list[tuple[int, int]]:
"""All stored intervals that overlap [start, end)."""
found: list[tuple[int, int]] = []
stack = [self.root] if self.root else []
while stack:
node = stack.pop()
if node.max_end <= start:
continue # nothing below ends after start
if node.start < end and start < node.end:
found.append((node.start, node.end))
if node.left:
stack.append(node.left)
if node.right and node.start < end: # right subtree starts at or after node.start
stack.append(node.right)
return sorted(found)
meetings = IntervalTree()
for start, end in [(9, 10), (13, 15), (10, 12), (16, 17), (11, 14), (8, 9)]:
meetings.insert(start, end)
print(meetings.overlapping(12, 13)) # [(11, 14)]
print(meetings.overlapping(9, 11)) # [(9, 10), (10, 12)]
print(meetings.overlapping(17, 18)) # []
This version is an unbalanced BST for clarity; in production, build it on a red-black or AVL tree and update max_end during rotations to keep the logarithmic bounds.
Walkthrough: overlapping(12, 13)
The root is (9, 10) with max_end 17.
Node
max_end
Overlaps [12, 13)?
Next
(9, 10)
17
no (ends at 10)
left (8, 9) and right (13, 15)
(13, 15)
17
no (starts at 13)
left (10, 12); right skipped since 13 ≥ 13
(10, 12)
14
no (ends at 12)
right (11, 14)
(11, 14)
14
yes
none
(8, 9)
9
skipped: max_end 9 ≤ 12
Complexity
Operation
Balanced interval tree
This unbalanced version
Insert
O(log n)
O(h)
Overlap query (all k)
O(min(n, k log n))
O(n) worst
Space
O(n)
O(n); the query stack is O(h)
Applications
Interval tree
Segment tree
Calendar conflicts and room booking
Range sum or min over an array with updates
Genome browsers (features overlapping a region)
Time-bucketed analytics with late data
Windowing systems (which windows contain a point)
Sweep-line area and coverage counting
Database temporal queries
Competitive programming range queries
Edge Cases
Empty or inverted intervals: rejected with ValueError.
Touching intervals[9, 10) and [10, 12): do not overlap with half-open semantics; use closed intervals and <= if touching should count.
Duplicates: allowed; equal starts go right.
Query with no overlaps: returns [] quickly when max_end prunes everything.
Interview Tips
Explain the max-end augmentation and the two pruning rules; that is the core idea.
Distinguish clearly: interval tree → find intervals; segment tree → aggregate over positions.
A common follow-up is “meeting rooms”: often solved with sorting and a heap, but an interval tree handles online inserts and queries.
51
Discuss the properties and uses of a Binary Indexed Tree (Fenwick Tree).
KnownRevise
A Fenwick tree (binary indexed tree) is an array-based structure that supports prefix sums and point updates in O(log n) each, using only n + 1 integers and a few lines of code. Each entry tree[i] stores the sum of a block of the original array whose length is the lowest set bit of i (i & -i). A prefix query sums O(log n) such blocks by repeatedly removing the lowest set bit; an update adds to O(log n) blocks by repeatedly adding it. It works for any operation with an inverse (sum, XOR, counts), which lets range queries be computed as differences of two prefixes.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Properties
Property
Detail
Storage
One array of size n + 1 (1-based); no pointers, no extra nodes
tree[i] covers
values[i − lowbit(i) + 1 … i] (1-based), where lowbit(i) = i & -i
Prefix query
Walk i → i − lowbit(i) until 0: at most ⌊log₂ n⌋ + 1 steps
Point update
Walk i → i + lowbit(i) until past n
Range sum [l, r)
prefix(r) − prefix(l)
Build
O(n) by pushing each total to its parent
Operations supported directly
Invertible ones (sum, XOR); min or max only in restricted forms
For n = 8, the blocks are:
i (binary)
lowbit
Covers (1-based)
1 (0001)
1
1
2 (0010)
2
1–2
3 (0011)
1
3
4 (0100)
4
1–4
5 (0101)
1
5
6 (0110)
2
5–6
7 (0111)
1
7
8 (1000)
8
1–8
Code Example
class FenwickTree:
"""Binary indexed tree for prefix sums with point updates (0-based API)."""
def __init__(self, size: int) -> None:
self.size = size
self.tree = [0] * (size + 1) # 1-based internally
@classmethod
def from_list(cls, values: list[int]) -> "FenwickTree":
"""Build in O(n) by pushing each node's total to its parent."""
fenwick = cls(len(values))
for i, value in enumerate(values, start=1):
fenwick.tree[i] += value
parent = i + (i & -i)
if parent <= fenwick.size:
fenwick.tree[parent] += fenwick.tree[i]
return fenwick
def add(self, index: int, delta: int) -> None:
"""values[index] += delta in O(log n)."""
i = index + 1
while i <= self.size:
self.tree[i] += delta
i += i & -i # move to the next node covering this index
def prefix_sum(self, count: int) -> int:
"""Sum of the first `count` values in O(log n)."""
total, i = 0, count
while i > 0:
total += self.tree[i]
i -= i & -i # drop the lowest set bit
return total
def range_sum(self, left: int, right: int) -> int:
"""Sum of values[left:right] (half-open)."""
return self.prefix_sum(right) - self.prefix_sum(left)
sales = [5, 3, 8, 6, 1, 4, 7, 2]
fenwick = FenwickTree.from_list(sales)
print(fenwick.prefix_sum(4)) # 22 (5 + 3 + 8 + 6)
print(fenwick.range_sum(2, 6)) # 19 (8 + 6 + 1 + 4)
fenwick.add(4, 9) # sales[4] becomes 10
print(fenwick.range_sum(2, 6)) # 28
print(fenwick.tree[1:]) # [5, 8, 8, 22, 10, 14, 7, 45]
Walkthrough: prefix_sum(6) Before the Update
Right after from_list, the internal array is [5, 8, 8, 22, 1, 5, 7, 36].
i (binary)
Adds tree[i]
Covers (1-based)
Running total
6 (110)
5
values 5–6: 1 + 4
5
4 (100)
22
values 1–4: 5 + 3 + 8 + 6
27
0
stop
27
Two steps instead of six. The update add(4, 9) walks i = 5 → 6 → 8, adding 9 to each, which is why the printed array ends with 10, 14, 7, 45.
Complexity
Operation
Time
Extra space
Build
O(n)
O(n) array
Point update
O(log n)
O(1)
Prefix / range sum
O(log n)
O(1)
Find smallest index with prefix ≥ target (non-negative values)
O(log n) by binary lifting
O(1)
No recursion is involved.
Fenwick Tree versus Segment Tree
Aspect
Fenwick tree
Segment tree
Code size
~15 lines
Longer
Memory
n + 1
2n to 4n
Operations
Invertible (sum, XOR, counts)
Any associative (min, max, GCD, custom)
Range updates
With two trees (range add, range sum)
Lazy propagation, general
Constant factor
Very small
Larger
Uses
Running totals with updates: scores, inventory counts, sales per day.
Counting inversions in O(n log n): process the array, querying how many larger values were seen.
Order statistics on a value range: frequency array plus “kth smallest” by binary lifting.
Range add, point query: store differences.
2-D Fenwick trees for prefix sums over grids with updates.
Edge Cases
Off-by-one errors: the internal array is 1-based; this API converts from 0-based indexes.
Empty array: valid; every sum is 0.
Negative values: fine for sums, but break the “find by prefix” binary lifting, which needs non-negative values.
Setting a value (rather than adding): add new − old, so keep the original values.
Interview Tips
Explain lowbit and the two walks (i −= i & -i for queries, i += i & -i for updates).
Say when you would choose it over a segment tree: sums with point updates, smallest code.
A common follow-up is counting inversions or “count of smaller numbers after self”.
52
What is a Suffix Tree, and why is it powerful for string processing?
KnownRevise
A suffix tree of a string S (length n) is a compressed trie of all suffixes of S: every path from the root spells a prefix of some suffix, edges are labelled with substrings, and each leaf marks where one suffix starts. Because every substring of S is a prefix of some suffix, a single walk from the root answers substring questions in time proportional to the pattern length, not the text length. It can be built in O(n) (Ukkonen’s or McCreight’s algorithm) and uses O(n) nodes, which makes many string problems linear: substring search, counting occurrences, longest repeated substring, and longest common substring of two strings.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Key Facts
Property
Value
Leaves
One per suffix: n (with a unique end marker $)
Internal nodes
At most n − 1, each with at least 2 children
Edge labels
Stored as (start, end) indexes into S, so space is O(n), not O(n²)
Construction
O(n) for a constant-size alphabet (Ukkonen, McCreight)
Substring test
O(m) for a pattern of length m
Count occurrences
O(m) with leaf counts stored per node
List all occurrences
O(m + occ)
The end marker $ guarantees that no suffix is a prefix of another, so every suffix ends at its own leaf.
Code Example: a Naive Suffix Trie
The optimised linear-time construction is long; this uncompressed suffix trie shows the idea on small strings. It costs O(n²) time and space, which a real suffix tree avoids by compressing single-child chains and building with Ukkonen’s algorithm.
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class TrieNode:
children: dict[str, TrieNode] = field(default_factory=dict)
count: int = 0 # how many suffixes pass through this node
def build_suffix_trie(text: str) -> TrieNode:
"""Naive suffix trie: insert every suffix. O(n^2) time and space; fine for small texts."""
root = TrieNode()
text += "$" # unique end marker
for start in range(len(text)):
node = root
for character in text[start:]:
node = node.children.setdefault(character, TrieNode())
node.count += 1
return root
def occurrences(root: TrieNode, pattern: str) -> int:
"""Number of times pattern occurs: walk it, then read the suffix count. O(m)."""
node = root
for character in pattern:
node = node.children.get(character)
if node is None:
return 0
return node.count
def longest_repeated_substring(root: TrieNode) -> str:
"""Deepest node shared by at least two suffixes."""
best = ""
stack = [(root, "")]
while stack:
node, path = stack.pop()
if len(path) > len(best):
best = path
for character, child in node.children.items():
if child.count >= 2 and character != "$":
stack.append((child, path + character))
return best
trie = build_suffix_trie("banana")
print(occurrences(trie, "ana"), occurrences(trie, "nab")) # 2 0
print(longest_repeated_substring(trie)) # ana
ana is a prefix of anana$ and ana$, so the node for a → n → a has count 2: two occurrences.
nab falls off the trie after n → a: zero occurrences.
The deepest node shared by at least two suffixes spells ana: the longest repeated substring.
Problems It Solves
Problem
With a suffix tree
Naive approach
Does P occur in S?
O(m) after O(n) build
O(n · m)
Count or list occurrences
O(m) or O(m + occ)
O(n · m)
Longest repeated substring
Deepest internal node, O(n)
O(n²) or worse
Longest common substring of S and T
Generalised suffix tree, O(n + m)
O(n · m) DP
Longest palindromic substring
Suffix tree of S and its reverse, O(n)
O(n²)
Number of distinct substrings
Sum of edge lengths, O(n)
O(n²)
Trade-offs and Alternatives
Structure
Build
Query P
Memory
Notes
Suffix tree
O(n)
O(m)
Large: often 10–20 bytes or more per character in practice
Fastest queries, complex code
Suffix array + LCP array
O(n) to O(n log n)
O(m log n), or O(m + log n) with LCP
About 4–8 bytes per character
Most common choice today
FM-index (BWT based)
O(n)
O(m)
Can be smaller than the text
Used in genome aligners
KMP / Z-algorithm per query
O(m)
O(n + m)
Small
Best for one-off searches
Memory is the main reason suffix arrays and FM-indexes often replace suffix trees for large texts such as genomes.
Complexity of the Example
build_suffix_trie inserts n + 1 suffixes of up to n + 1 characters: O(n²) time and nodes. occurrences is O(m). longest_repeated_substring visits each node once: O(n²) for the uncompressed trie, O(n) on a real suffix tree. The code is iterative.
Edge Cases
Empty text: only the $ suffix; every non-empty pattern occurs 0 times.
Empty pattern: returns the root’s count, which is 0 here; define it as n + 1 positions if needed.
Repeated characters ("aaaa"): the uncompressed trie is quadratic, the compressed tree stays linear.
Marker collision: choose an end marker that cannot appear in the text.
Interview Tips
Say “compressed trie of all suffixes; every substring is a prefix of a suffix; O(n) build, O(m) search”.
Mention suffix arrays as the memory-efficient alternative most people use in practice.
Interviewers rarely expect Ukkonen’s algorithm; they expect the uses (longest repeated or common substring) and the complexity.
53
Why are B-Trees used for Databases and File Systems?
KnownRevise
Databases and file systems keep data on storage that is read in blocks (pages of 4–16 KiB, sometimes more), where fetching a block costs far more than comparing keys in memory. B-trees (and the B+ tree variant most systems use) are designed for exactly that: each node fills one page and holds hundreds of keys, so the tree is only 3–4 levels deep for billions of keys. A lookup therefore needs only a few page reads, the top levels stay cached in memory, keys are sorted for range scans and ORDER BY, and the tree stays balanced automatically as data is inserted and deleted.
Read full answerHide full answer
Applies todatabase storage engines (InnoDB, PostgreSQL, SQLite, SQL Server) and file systems (NTFS, XFS, Btrfs, APFS-style designs)
The Core Reason: Cost per Level
Operation (rough orders of magnitude)
Time
Comparing two keys in memory
~1–10 ns
Reading a page from a cached buffer pool
~100 ns to 1 µs
Reading a page from an SSD
~100 µs
Reading a page from a spinning disk
~5–10 ms
When a node read can be a thousand to a million times slower than a comparison, the goal is fewest node reads, not fewest comparisons. A B-tree trades more comparisons inside each node (cheap, binary search) for far fewer levels (expensive).
Keys
Binary tree height
B+ tree, ~500 keys per node
1 million
~20
3
1 billion
~30
4
Properties That Fit Storage
Property
Why it matters
Node size matches page size
One I/O fetches a whole node
High fanout
Shallow tree, few I/Os per lookup
All leaves at the same depth
Every lookup has a predictable cost
Sorted keys within and across nodes
Range queries, prefix searches, ordered scans, merge joins
Linked leaves (B+ tree)
Range scans become sequential reads along the leaf level
Nodes at least half full
Space efficiency and bounded height
Local changes on update
An insert usually touches one leaf; splits are rare and local
Grows at the root
Balance without global rebuilds
Works with write-ahead logging and page-level locking
Crash recovery and concurrency at page granularity
How Databases Use Them
Primary (clustered) index: in engines such as InnoDB, the table’s rows live in the leaves of a B+ tree keyed by the primary key, so rows are stored in key order.
Secondary indexes: leaves map the indexed column to a row identifier or the primary key.
Composite indexes(customer_id, created_at) support “all orders for a customer, newest first” with one range scan.
Covering indexes answer a query from the index alone, without touching the table.
CREATE INDEX idx_orders_customer_date ON orders (customer_id, created_at);
-- One descent to the first matching leaf, then a sequential scan along linked leaves:
SELECT id, total FROM orders
WHERE customer_id = 42 AND created_at >= '2026-01-01'
ORDER BY created_at;
How File Systems Use Them
Directory entries indexed by name, so lookups in folders with millions of files stay fast (NTFS, XFS, ext4’s HTree is a related hashed tree).
Extent maps: which disk blocks hold which part of a file.
Free-space tracking and metadata in copy-on-write file systems such as Btrfs, which use B-trees where modified nodes are written to new locations.
Alternatives and When They Win
Structure
Strength
Weakness compared with B-trees
Hash index
O(1) exact lookups
No range queries or ordering
LSM tree (RocksDB, Cassandra)
Very high write throughput: sequential writes, batched merges
Reads may check several levels; compaction cost
Binary search trees
Simple in memory
Too deep for disk; poor cache use
Sorted file with binary search
Compact
Expensive inserts
Many write-heavy systems choose LSM trees; read-heavy and mixed OLTP systems usually choose B+ trees.
Interview Tips
Lead with “minimise I/Os: one node per page, high fanout, 3–4 levels for billions of keys”.
Add range scans (sorted, linked leaves) and predictable balanced height.
A common follow-up is B-tree versus LSM tree for write-heavy workloads, or why a hash index cannot serve ORDER BY or BETWEEN.
54
When might standard BSTs be preferred over AVL trees?
KnownRevise
A plain BST can be the better choice when the tree’s shape will stay good without active balancing, or when balancing costs more than it saves: keys arrive in random order (expected height about 1.39 log₂ n), the tree is built once from known data in a balanced way and then mostly read, the data set is small, or the code must be minimal and easy to verify. When inputs can be sorted, adversarial or long-lived with many updates, an AVL or red-black tree (or the language’s library map) is the safer choice.
Read full answerHide full answer
Applies tolanguage-independent
Situations Where a Plain BST Is Reasonable
Situation
Why a plain BST works
Keys inserted in random order (shuffled, hashed or random IDs)
Expected height O(log n); no rotations or height bookkeeping
Static data built once
Build a perfectly balanced tree from sorted keys (middle element as root) in O(n); it never changes
Small trees (tens to a few hundred nodes)
Height differences cost only a few comparisons
Teaching, prototypes, interview warm-ups
Shortest correct code
Memory-constrained nodes
No height, balance factor or colour field
Heavy bulk updates followed by reads
Rebuild the tree in O(n) after each batch instead of rebalancing every insert
Need to control the shape for other reasons
Expression trees, decision trees or tries with BST-ordered children
What AVL Trees Cost
Cost
Detail
Per-node data
A height or balance factor
Insert
Height updates along the path, plus up to one single or double rotation
Delete
Possibly a rotation at several levels
Code complexity
Four rotation cases; deletion is error-prone
Constant factors
Extra work on every update even when the tree is already balanced
For random inserts, a plain BST’s expected search depth is about 1.39 log₂ n, while an AVL tree’s worst case is about 1.44 log₂ n and its typical depth is close to log₂ n. The difference in lookups is often a few comparisons, while the AVL tree pays for rebalancing on every update.
Input can be controlled by users or attackers: they can force the worst case.
The structure lives a long time with many deletions: repeated successor-based deletes can skew it.
You need predictable latency for every operation.
In those cases use a self-balancing tree. For a read-heavy workload, AVL; for update-heavy, red-black; for disk, a B+ tree.
Practical Advice
In production code, the choice is usually neither: use the language’s ordered map (std::map, TreeMap) or, in Python, dict for exact lookups and a sorted list with bisect (or sortedcontainers) for ordered access.
Writing your own plain BST makes sense when you need custom augmentation (subtree sizes, interval max-ends) and control the input order, or rebuild periodically.
If you must accept arbitrary order but want simple code, a treap gives expected O(log n) with little more code than a plain BST.
Complexity Summary
Plain BST, random keys
Plain BST, sorted keys
AVL
Search
O(log n) expected
O(n)
O(log n) worst case
Insert
O(log n) expected
O(n)
O(log n) worst case
Delete
O(log n) expected
O(n)
O(log n) worst case
Extra per node
none
none
height or balance factor
Interview Tips
Show judgement: “plain BST when the input order is random or the tree is static; otherwise self-balancing”.
Mention the expected height of a random BST and the balanced rebuild option for static data.
A frequent mistake is the blanket claim that a plain BST is always worse; the honest answer depends on the input distribution and update pattern.
55
Why do databases index data with B-Trees instead of Hash Tables?
KnownRevise
Hash tables answer exact-match lookups in O(1) on average, but databases need much more from an index: range queries (BETWEEN, >, <), sorting (ORDER BY), prefix searches (LIKE 'abc%'), composite-key lookups on a leading column, and predictable performance as the data grows on disk. A hash scatters keys randomly, so it cannot do any of these without scanning everything. A B+ tree keeps keys sorted in shallow, page-sized nodes, so it handles exact lookups in a few page reads and all the ordered operations. That is why B+ trees are the default index type, while hash indexes are an option for pure equality lookups.
Resizing or rehashing large on-disk tables is expensive
Worst case
Logarithmic, balanced
Degrades with collisions or skewed keys
Concurrency and recovery
Mature page-level locking and logging
Harder for on-disk growth
Why “O(1) Versus O(log n)” Matters Less on Disk
On disk, cost is counted in page reads, not comparisons. A B+ tree over a billion rows is about 4 levels; the root and the next level are almost always in the buffer cache, so an exact lookup costs about one or two real I/Os, close to what a disk-based hash index needs. The B+ tree gives up very little on equality lookups and gains every ordered operation.
Example
CREATE TABLE orders (
id BIGINT PRIMARY KEY, -- B+ tree (clustered in InnoDB)
customer_id BIGINT NOT NULL,
created_at TIMESTAMP NOT NULL,
total NUMERIC(10, 2) NOT NULL
);
CREATE INDEX idx_orders_customer_created ON orders (customer_id, created_at);
-- Uses the B+ tree: equality on the first column, range plus order on the second.
SELECT id, total FROM orders
WHERE customer_id = 42 AND created_at >= '2026-10-01'
ORDER BY created_at DESC
LIMIT 20;
-- PostgreSQL also offers hash indexes for pure equality on a column:
CREATE INDEX idx_orders_session_hash ON orders USING HASH (customer_id);
The hash index can serve customer_id = 42 but not the date range, the ordering or the LIMIT shortcut.
Where Hashing Is Used Anyway
In-memory hash joins and hash aggregation inside query execution.
Hash indexes for equality-only columns (PostgreSQL; MySQL’s MEMORY engine; InnoDB’s internal adaptive hash index on hot B+ tree pages).
Key-value stores whose API is only get and put by key, often in memory.
Partitioning or sharding by hash of a key to spread load across servers, with B+ trees or LSM trees inside each shard.
Trade-offs
Choose a B+ tree when
Choose a hash index when
Any range, sort, prefix or min/max query may appear
Lookups are only = on a full key
Queries will evolve over time
The access pattern is fixed and very hot
Data lives on disk and grows unpredictably
Data fits in memory and size is stable
Interview Tips
Lead with “order”: hashing destroys key order, and most real queries need it.
Then the I/O argument: a shallow B+ tree costs about the same number of disk reads as a hash lookup.
A common follow-up is the leftmost-prefix rule for composite indexes, or when you would pick an LSM tree (write-heavy workloads).
56
Why are Red-Black Trees important for associative containers in the C++ STL?
KnownRevise
The C++ standard requires the ordered associative containers (std::map, std::set, std::multimap, std::multiset) to keep keys sorted, to perform insert, erase and lookup in O(log n) worst case, and to keep iterators and references valid when other elements are inserted or erased. The standard does not name a data structure, but a red-black tree meets all three requirements with few rotations per update, so the major implementations (libstdc++, libc++ and Microsoft’s STL) all use one. That is why std::map gives ordered iteration and lower_bound that std::unordered_map (a hash table) cannot.
Read full answerHide full answer
Applies toC++20 standard library (`<map>`, `<set>`)
What the Standard Requires, and How a Red-Black Tree Delivers It
Requirement
Red-black tree property
Keys kept in sorted order, iteration in key order
BST ordering; in-order traversal through parent pointers
find, insert, erase in O(log n) worst case
Height ≤ 2 log₂(n + 1)
lower_bound, upper_bound, equal_range in O(log n)
Ordered descent
Insert and erase do not invalidate other iterators or references
Node-based: elements never move in memory; rebalancing only changes pointers and colours
Amortized O(1) insert with a correct hint
Insert next to the hinted node, then fix up locally
Bidirectional iterators
Parent pointers allow ++ and -- without a stack
Node handles (extract, merge in C++17)
Nodes can be unlinked and relinked without copying elements
Why Red-Black Rather Than AVL
Bounded restructuring: at most 2 rotations per insert and 3 per erase, with recolouring that is O(1) amortized. AVL may rotate at several levels on erase.
One colour bit per node, which implementations can pack into spare pointer bits.
Mature, well-tested code shared across map, set, multimap and multiset (one generic tree type in each library).
Lookups are slightly deeper than in an AVL tree, but still logarithmic; general-purpose containers see a mix of updates and lookups.
Code Example
#include <iostream>
#include <map>
#include <set>
#include <string>
int main() {
// Ordered map: keys kept sorted, O(log n) insert, find and erase.
std::map<int, std::string> orders{{1005, "pending"}, {1001, "shipped"}, {1003, "paid"}};
orders.emplace(1002, "paid");
for (const auto& [id, status] : orders) { // in-order traversal: sorted keys
std::cout << id << ':' << status << ' ';
}
std::cout << '\n'; // 1001:shipped 1002:paid 1003:paid 1005:pending
auto it = orders.lower_bound(1004); // first key >= 1004, O(log n)
std::cout << it->first << '\n'; // 1005
auto keep = orders.find(1003); // iterator stays valid...
orders.erase(1001); // ...when other elements are erased
orders.emplace(1000, "new"); // ...or inserted (no rehash, no reallocation)
std::cout << keep->second << '\n'; // paid
std::set<int> seen{5, 1, 4};
std::cout << *seen.begin() << ' ' << *seen.rbegin() << '\n'; // 1 5
return 0;
}
Compiled with -std=c++20 -Wall -Wextra, this prints sorted keys, the lower_bound result 1005, paid through an iterator that stayed valid across an erase and an insert, and the smallest and largest elements of the set.
std::map versus std::unordered_map
Aspect
std::map (red-black tree)
std::unordered_map (hash table)
Lookup
O(log n) worst case
O(1) average, O(n) worst case
Ordered iteration, lower_bound
Yes
No
Iterator invalidation
Only the erased element’s iterators
All iterators on rehash
Key requirements
operator< (strict weak ordering)
std::hash and operator==
Memory per element
Node with 3 pointers and a colour
Node plus bucket array
Cache behaviour
Pointer chasing per level
Usually better for lookups
Choose std::map for ordered data, range queries, stable iterators or worst-case guarantees; choose std::unordered_map for fast exact lookups. For small, mostly read-only data, a sorted std::vector with std::lower_bound (or C++23 std::flat_map) often beats both because of cache locality.
Complexity
Operation
std::map
find, count, contains (C++20)
O(log n)
insert, emplace, erase(key)
O(log n)
erase(iterator)
Amortized O(1)
lower_bound, upper_bound
O(log n)
Full iteration
O(n)
Memory
O(n) nodes
Edge Cases and Pitfalls
operator[]inserts a default value for a missing key; use find or contains when you only want to check.
The comparator must be a strict weak ordering; an inconsistent comparator breaks the tree’s invariants and is undefined behaviour.
Modifying a key in place is not allowed (keys are const); use extract, change the key, and reinsert.
std::multimap keeps equal keys in insertion order within the equal range.
Interview Tips
Say that the standard specifies complexity and iterator stability, and a red-black tree is the structure that satisfies them in practice.
Explain why red-black beats AVL here: bounded rotations on erase.
Expect map versus unordered_map, and when a sorted vector is the better choice.
57
Write an algorithm to generate a Mirror of a Binary Tree.
KnownRevise
The mirror of a binary tree is the tree you get by swapping the left and right children of every node, so it looks like the original reflected left to right. The algorithm visits every node once and swaps its two child pointers. Recursively, that is mirror(left) and mirror(right) with the results swapped; iteratively, it is any traversal (stack or queue) that swaps children as it pops each node. Both take O(n) time; the recursive version uses O(h) stack space, and the iterative one avoids recursion-depth limits on deep trees.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def level_order(root: Node | None) -> list[int]:
out, queue = [], deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.val)
queue.extend(c for c in (node.left, node.right) if c)
return out
def mirror(root: Node | None) -> Node | None:
"""Mirror the tree in place (recursive): swap children at every node."""
if root is None:
return None
root.left, root.right = mirror(root.right), mirror(root.left)
return root
def mirror_iterative(root: Node | None) -> Node | None:
"""Same result without recursion, safe for very deep trees."""
stack = [root] if root else []
while stack:
node = stack.pop()
node.left, node.right = node.right, node.left
stack.extend(c for c in (node.left, node.right) if c)
return root
tree = build([4, 2, 7, 1, 3, 6, 9])
print(level_order(mirror(tree))) # [4, 7, 2, 9, 6, 3, 1]
print(level_order(mirror_iterative(tree))) # [4, 2, 7, 1, 3, 6, 9] (mirrored back)
print(mirror(None)) # None
build creates a tree from level-order values (with None for missing children) and level_order prints it, so the result is easy to check.
Level order of the mirror is [4, 7, 2, 9, 6, 3, 1]. Mirroring twice restores the original, which the second print shows.
Complexity
Recursive
Iterative
Time
O(n): each node swapped once
O(n)
Space
O(h) call stack: O(log n) balanced, O(n) skewed
O(n) worst case for the explicit stack
Variants
Return a new tree instead of changing the input: Node(root.val, mirror_copy(root.right), mirror_copy(root.left)). This costs O(n) extra memory but keeps the original intact, which matters when other code still holds references.
Check whether two trees are mirrors of each other: compare a.left with b.right and a.right with b.left recursively.
Symmetric tree check: a tree is symmetric when it is a mirror of itself.
An in-order traversal of the mirror is the reverse of the original in-order sequence; for a BST, mirroring turns ascending order into descending order.
Edge Cases
Empty tree: returns None.
Single node: nothing to swap.
Skewed tree (a chain of 100,000 nodes): the recursive version exceeds Python’s default recursion limit of 1,000; use the iterative version.
Shared subtrees (a DAG rather than a tree): in-place swapping would visit a shared node twice and swap it back; real trees do not share nodes.
Common Pitfalls
Writing root.left = mirror(root.right) and then root.right = mirror(root.left) as two separate statements: the second line reads the already overwritten root.left. Use a simultaneous assignment or a temporary variable.
Forgetting to return the root, so the caller loses the tree.
Mirroring a BST and still searching it with the original ordering.
Interview Tips
State “swap children at every node, any traversal order works”, then write the recursive version in a few lines.
Offer the iterative version and mention recursion depth for skewed trees.
Ask whether the input may be modified; if not, build a mirrored copy.
58
How to determine if two binary trees are Isomorphic?
KnownRevise
Two binary trees are isomorphic if one can be turned into the other by swapping the left and right children of any number of nodes. The recursive test follows directly: two empty trees are isomorphic; otherwise the roots must hold equal values, and their children must match either as they are (left with left, right with right) or swapped (left with right, right with left). A faster alternative builds a canonical form for each tree, sorting each node’s child signatures so child order no longer matters, and compares the two forms.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def isomorphic(a: Node | None, b: Node | None) -> bool:
"""True if b can be made identical to a by swapping children at any nodes."""
if a is None or b is None:
return a is b
if a.val != b.val:
return False
return (isomorphic(a.left, b.left) and isomorphic(a.right, b.right)) or (
isomorphic(a.left, b.right) and isomorphic(a.right, b.left)
)
def canonical(root: Node | None) -> tuple:
"""Shape-and-value signature that ignores child order: O(n log n) comparison."""
if root is None:
return ()
kids = sorted((canonical(root.left), canonical(root.right)))
return (root.val, *kids)
a = build([1, 2, 3, 4, 5, 6, None, None, None, 7, 8])
b = build([1, 3, 2, None, 6, 4, 5, None, None, None, None, 8, 7])
c = build([1, 2, 3, 4, 5, 6, 7])
print(isomorphic(a, b), isomorphic(a, c)) # True False
print(canonical(a) == canonical(b)) # True
Walkthrough
Tree a Tree b
1 1
/ \ / \
2 3 3 2
/ \ / \ / \
4 5 6 6 4 5
/ \ / \
7 8 8 7
Pair compared
Values equal?
Match found
(1, 1)
yes
children match swapped: a.2 with b.2, a.3 with b.3
(3, 3)
yes
a.3 has left 6; b.3 has right 6: swapped
(2, 2)
yes
4 with 4, 5 with 5: as they are
(5, 5)
yes
7 and 8 appear in the opposite order: swapped
Tree c has a node 7 under 3 that a does not have, so the shapes differ and the test returns False.
Complexity
Method
Time
Space
Recursive with both orders
O(n) in many cases; the “or” can re-explore subtrees, giving a worst case above linear (polynomial in n)
O(h) call stack
Canonical form with sorting
O(n log n) overall
O(n) for the signatures
Canonical form with AHU-style integer labels
O(n log n) or O(n) with hashing tricks
O(n)
The recursive version fails fast in practice because values must match before it recurses, so most mismatched branches stop at the first compare.
Related Definitions
Term
Meaning
Identical trees
Same shape and values, no swaps allowed
Isomorphic (this problem)
Identical after swapping children at any nodes
Mirror trees
Identical after swapping children at every node
Structurally isomorphic
Same as isomorphic, but values ignored (compare shapes only)
Edge Cases
Both empty: isomorphic. Exactly one empty: not.
Different sizes: never isomorphic; checking node counts first is a cheap early exit.
Duplicate values: handled, since each pair of subtrees is compared structurally.
Shape-only variant: remove the value comparison.
Common Pitfalls
Checking only the swapped case, or only the unswapped case.
Returning a == b on None checks without handling the “exactly one is None” case (the code uses a is b).
Comparing in-order traversals: different trees can share them, and swapping changes them.
Interview Tips
State the recurrence first: equal roots and (children match straight or children match swapped).
Mention the canonical-form approach for guaranteed O(n log n), and for comparing many trees (group them by signature).
Ask whether values matter or only the shape.
59
Implement an algorithm to check if a binary tree is a Valid BST.
KnownRevise
A binary tree is a valid BST when, for every node, all values in its left subtree are smaller and all values in its right subtree are larger. Checking only each node against its direct children is the classic mistake, because a deep descendant can still violate an ancestor’s limit. The correct method passes lower and upper bounds down the tree: going left tightens the upper bound to the node’s value, going right tightens the lower bound. An equivalent check is that an in-order traversal is strictly increasing. Both run in O(n) time.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
import math
def is_valid_bst(root: Node | None) -> bool:
"""Every node must lie strictly inside the (low, high) bounds set by its ancestors."""
stack = [(root, -math.inf, math.inf)]
while stack:
node, low, high = stack.pop()
if node is None:
continue
if not low < node.val < high:
return False
stack.append((node.left, low, node.val))
stack.append((node.right, node.val, high))
return True
def is_valid_bst_inorder(root: Node | None) -> bool:
"""Alternative: an in-order walk must be strictly increasing."""
stack, prev, node = [], -math.inf, root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if node.val <= prev:
return False
prev, node = node.val, node.right
return True
good = build([8, 3, 10, 1, 6, None, 14, None, None, 4, 7])
trap = build([8, 3, 10, 1, 9]) # 9 is a valid child of 3 but sits in 8's left subtree
print(is_valid_bst(good), is_valid_bst(trap)) # True False
print(is_valid_bst_inorder(good), is_valid_bst_inorder(trap)) # True False
print(is_valid_bst(build([5, 5]))) # False (duplicates rejected)
Both versions are iterative, so they also work on very deep trees.
Why the Bounds Matter
8
/ \
3 10
/ \
1 9 <- 9 > 3, so it is a fine right child of 3,
but it is in 8's left subtree, so it must be < 8
Node
Bounds (low, high) inherited
Check
Result
8
(−∞, ∞)
−∞ < 8 < ∞
ok
10
(8, ∞)
8 < 10 < ∞
ok
3
(−∞, 8)
−∞ < 3 < 8
ok
9
(3, 8)
3 < 9 < 8
fails
A child-only check (left < node < right) would accept this tree.
Complexity
Bounds method
In-order method
Time
O(n), stops at the first violation
O(n), stops at the first violation
Space
O(h) stack entries, about one pending sibling per level: O(log n) balanced, O(n) skewed
O(h)
Choosing Between the Two
Bounds
In-order
Works directly with per-node constraints
Uses the defining property of BSTs: sorted in-order output
Easy to adapt for allowed duplicates on one side (low <= val < high)
Duplicate rules need care in the comparison
Order of visiting nodes does not matter
Must visit in order
Edge Cases
Empty tree: valid.
Duplicates: the strict comparisons reject them. If your BST allows duplicates on one side, change one comparison to <= and document it.
Extreme values (for example 64-bit minimum and maximum in Java or C++): initial bounds of Integer.MIN_VALUE would wrongly reject a node holding that value. Use None or nullable bounds, long, or infinity as here.
Non-numeric keys: works with any comparable type; replace infinities with None checks.
Common Pitfalls
Comparing a node only with its children.
Using <= in one place and < in another, giving inconsistent duplicate handling.
Storing in-order output in a list and then checking it: correct but O(n) extra space; compare with prev as you go.
Using sentinel integers that can collide with real values.
Interview Tips
Draw the “9 under 3 under 8” counterexample to show you know the trap.
Write the bounds version first, then mention the in-order alternative.
Ask about duplicates and value range before coding.
60
Solve the Lowest Common Ancestor (LCA) problem in a Binary Tree.
KnownRevise
The lowest common ancestor of nodes p and q is the deepest node that has both as descendants (a node counts as its own descendant). In a general binary tree, a single post-order pass solves it in O(n): each call returns p or q if it finds one in that subtree; the first node where both the left and right calls return something is the LCA, and if only one side returns something, that result is passed up. In a BST, you can use the ordering instead: walk down from the root until p and q fall on different sides, in O(h) time and O(1) space.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def lowest_common_ancestor(root: Node | None, p: Node, q: Node) -> Node | None:
"""LCA in a general binary tree; assumes both p and q are in the tree."""
if root is None or root is p or root is q:
return root
left = lowest_common_ancestor(root.left, p, q)
right = lowest_common_ancestor(root.right, p, q)
if left and right:
return root # p and q are on different sides
return left or right
def lca_bst(root: Node | None, p: int, q: int) -> Node | None:
"""In a BST, walk down until p and q split: O(h) time, O(1) space."""
node = root
while node:
if p < node.val and q < node.val:
node = node.left
elif p > node.val and q > node.val:
node = node.right
else:
return node
return None
def find(root: Node | None, val: int) -> Node | None:
stack = [root] if root else []
while stack:
node = stack.pop()
if node.val == val:
return node
stack.extend(c for c in (node.left, node.right) if c)
return None
tree = build([3, 5, 1, 6, 2, 0, 8, None, None, 7, 4])
print(lowest_common_ancestor(tree, find(tree, 5), find(tree, 1)).val) # 3
print(lowest_common_ancestor(tree, find(tree, 7), find(tree, 4)).val) # 2
print(lowest_common_ancestor(tree, find(tree, 5), find(tree, 4)).val) # 5
bst = build([6, 2, 8, 0, 4, 7, 9, None, None, 3, 5])
print(lca_bst(bst, 3, 5).val, lca_bst(bst, 2, 8).val) # 4 6
Walkthrough: LCA(7, 4)
3
/ \
5 1
/ \ / \
6 2 0 8
/ \
7 4
Call at
Left returns
Right returns
Returns
7
7 (it is p)
4
4 (it is q)
2
7
4
2: found on both sides
6
None
None
None
5
None
2
2 (passes it up)
1
None
None
None
3
2
None
2
For LCA(5, 4), the call at 5 returns 5 immediately, because a node is its own ancestor; 4 is somewhere below it.
Complexity
Method
Time
Space
Requirement
Recursive, general tree
O(n)
O(h) call stack
Both nodes present
BST walk
O(h)
O(1)
BST ordering
Parent pointers
O(h)
O(h) set, or O(1) by aligning depths
Each node knows its parent
Binary lifting
O(n log n) preprocessing, O(log n) per query
O(n log n)
Many queries on a static tree
Euler tour + sparse table (range minimum)
O(n log n) preprocessing, O(1) per query
O(n log n)
Many queries
Edge Cases
p is an ancestor of q: returns p, as the 5 and 4 example shows.
p == q: returns that node.
A node is missing from the tree: the basic version returns the other node, which is wrong. Track two found flags during the traversal, or check that both nodes exist first.
Duplicate values: compare node identity (is), not values, in a general tree.
Very deep trees: convert to an iterative traversal with parent pointers to avoid recursion limits.
Common Pitfalls
Using the BST shortcut on a tree that is not a BST.
Comparing values instead of nodes when values repeat.
Assuming the root is always the answer when the nodes are in different subtrees of the root, without handling the case where one node is the root itself.
Applications
Distance between two nodes: depth(p) + depth(q) − 2 · depth(lca).
Version control: the merge base of two commits (an LCA in a DAG).
Organisation charts and file systems: the nearest shared manager or directory.
Phylogenetics: the most recent common ancestor of two species.
Interview Tips
Start with the recursive O(n) version and explain the “found on both sides” rule.
Ask whether the tree is a BST or has parent pointers; both give simpler O(h) solutions.
Mention binary lifting when there are many queries.
61
Write a code to find the Height of a Binary Tree.
KnownRevise
The height of a binary tree is the number of edges on the longest path from the root to a leaf (some texts count nodes instead, which adds 1). The recursive definition is direct: an empty tree has height −1 (or 0 when counting nodes), and any other tree has height 1 + max(height(left), height(right)). An iterative level-order traversal counts levels instead and avoids recursion limits on deep trees. Both visit every node once, so they run in O(n) time.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
from collections import deque
def height(root: Node | None) -> int:
"""Height in edges: -1 for an empty tree, 0 for a single node."""
if root is None:
return -1
return 1 + max(height(root.left), height(root.right))
def height_iterative(root: Node | None) -> int:
"""Level-order: count levels, then convert to edges. Safe for deep trees."""
levels, queue = 0, deque([root] if root else [])
while queue:
levels += 1
for _ in range(len(queue)):
node = queue.popleft()
queue.extend(c for c in (node.left, node.right) if c)
return levels - 1
tree = build([1, 2, 3, 4, 5, None, None, 8])
print(height(tree), height_iterative(tree)) # 3 3
print(height(None), height(build([42]))) # -1 0
chain = Node(0)
node = chain
for i in range(1, 5000): # a 5,000-node chain
node.right = Node(i)
node = node.right
print(height_iterative(chain)) # 4999 (recursion would hit Python's limit)
The level-order version sees 4 levels (0 to 3) and returns 4 − 1 = 3.
Edges or Nodes?
Tree
Height in edges
Height in nodes (also called “max depth”)
Empty
−1
0
Single node
0
1
Example above
3
4
Always say which convention you use; many coding platforms ask for maximum depth in nodes. Switch by returning 0 for None instead of -1.
Complexity
Recursive
Level order
Time
O(n)
O(n)
Space
O(h) call stack: O(log n) balanced, O(n) skewed
O(w), where w is the widest level (up to about n/2 for a complete tree)
Edge Cases
Empty tree: −1 in edges, 0 in nodes.
Skewed trees: recursion depth equals the height; Python’s default limit is about 1,000, so the 5,000-node chain uses the iterative version.
Very wide trees: the queue holds a whole level; a depth-first iterative version with an explicit (node, depth) stack uses O(h) memory instead.
Related Problems
Minimum depth: shortest root-to-leaf path. Use BFS and stop at the first leaf; with recursion, ignore missing children rather than taking min with them.
Balanced check: compute heights bottom-up and stop as soon as two sibling heights differ by more than 1, in O(n).
Diameter: for each node, the sum of its two child heights, which is the next question in this set.
Common Pitfalls
Mixing edge and node conventions between the base case and the answer.
Computing height separately at every node inside another recursion (for a balance or diameter check), which gives O(n²); compute it once bottom-up.
Recursing on deep, skewed trees in languages with small stacks.
Interview Tips
Write the three-line recursive solution, then state the convention you chose.
Offer the BFS version and mention the recursion-depth risk.
Expect the follow-ups: minimum depth, balanced check, diameter.
62
What is the Diameter of a Tree?
KnownRevise
The diameter of a tree is the length of the longest path between any two nodes, usually counted in edges. That path does not have to pass through the root. For a binary tree, compute it in one post-order pass: at each node, the longest path that bends there is depth(left) + depth(right); the diameter is the largest such value over all nodes, and each call returns 1 + max(depth(left), depth(right)) to its parent. For any general tree, two BFS passes also work: from any node, find the farthest node u; the farthest distance from u is the diameter. Both run in O(n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def diameter(root: Node | None) -> int:
"""Longest path between any two nodes, counted in edges."""
best = 0
def depth(node: Node | None) -> int:
"""Number of nodes on the longest downward path from node."""
nonlocal best
if node is None:
return 0
left, right = depth(node.left), depth(node.right)
best = max(best, left + right) # path that bends at this node
return 1 + max(left, right)
depth(root)
return best
def diameter_general(adjacency: dict[int, list[int]]) -> int:
"""For any tree given as an adjacency list: BFS twice from the farthest node."""
def farthest(start: int) -> tuple[int, int]:
dist, frontier = {start: 0}, [start]
while frontier:
nxt = []
for u in frontier:
for v in adjacency[u]:
if v not in dist:
dist[v] = dist[u] + 1
nxt.append(v)
frontier = nxt
node = max(dist, key=dist.get)
return node, dist[node]
end, _ = farthest(next(iter(adjacency)))
return farthest(end)[1]
print(diameter(build([1, 2, 3, 4, 5]))) # 3 (4 -> 2 -> 1 -> 3)
lopsided = build([1, 2, None, 3, 4, 5, None, None, 6])
print(diameter(lopsided)) # 4 (5 -> 3 -> 2 -> 4 -> 6), not through the root
print(diameter(None), diameter(build([7]))) # 0 0
graph = {1: [2], 2: [1, 3, 4], 3: [2], 4: [2, 5], 5: [4, 6], 6: [5]}
print(diameter_general(graph)) # 4
Walkthrough: Not Through the Root
1
/
2
/ \
3 4
/ \
5 6
Node
depth(left)
depth(right)
Path bending here
Returns
5
0
0
0
1
3
1
0
1
2
6
0
0
0
1
4
0
1
1
2
2
2
2
4
3
1
3
0
3
4
The longest path is 5 → 3 → 2 → 4 → 6, with 4 edges, and it bends at node 2 rather than the root.
Why Two BFS Passes Work (General Trees)
From any start node, the farthest node u must be an endpoint of some longest path. This holds in trees because there is exactly one path between any two nodes. A second search from u then reaches the other end of that path. This works for any tree, including unbalanced and non-binary ones, when it is stored as an adjacency list. With weighted edges, use DFS distances instead of BFS levels.
Complexity
Method
Time
Space
Post-order on a binary tree
O(n)
O(h) call stack
Two BFS on an adjacency list
O(n)
O(n)
Naive (height at every node from scratch)
O(n²) on skewed trees
O(h)
Edges or Nodes?
Some problems count nodes on the path, which is edges + 1. In the code, left + right counts edges; use left + right + 1 to count nodes.
Edge Cases
Empty tree or one node: 0.
Skewed chain of n nodes: n − 1; the recursion is as deep as the tree, so use an iterative post-order for very deep inputs.
Several longest paths: the length is the same; return any one if the path itself is needed (track the bending node and rebuild).
Weighted edges: sum the weights instead of counting edges; the two-pass trick still works with non-negative weights.
Applications
Network latency: the worst-case hop count between any two nodes in a tree-shaped network.
Tree centre: the middle of a diameter path, used to pick a root that minimises height.
Competitive programming: a building block for many tree problems.
Common Pitfalls
Returning height(left) + height(right)at the root only, which misses paths that bend elsewhere.
Recomputing heights in a nested way, giving O(n²).
Mixing the “nodes” and “edges” definitions.
Interview Tips
Say “the longest path may not pass through the root” before coding.
Show the single pass with a shared best variable updated at every node.
Mention the two-BFS method for general trees.
63
How would you find the Maximum Path Sum in a Binary Tree?
KnownRevise
The maximum path sum problem asks for the largest sum of node values along any path: a sequence of connected nodes, each used at most once, that can start and end anywhere and must contain at least one node. Values can be negative. The solution is one post-order pass. Each call computes the best downward sum starting at its node (its value plus the better child branch, where a negative branch counts as 0) and returns that to its parent. Along the way, it updates a global answer with the best path that bends at the node: value + left gain + right gain. Time is O(n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
import math
def max_path_sum(root: Node) -> int:
"""Largest sum of node values on any path (at least one node, any start and end)."""
best = -math.inf
def gain(node: Node | None) -> int:
"""Best sum of a downward path starting at node; never below 0 for the parent."""
nonlocal best
if node is None:
return 0
left = max(gain(node.left), 0) # drop a branch that would lower the sum
right = max(gain(node.right), 0)
best = max(best, node.val + left + right)
return node.val + max(left, right)
gain(root)
return best
print(max_path_sum(build([1, 2, 3]))) # 6
print(max_path_sum(build([-10, 9, 20, None, None, 15, 7]))) # 42 (15 -> 20 -> 7)
print(max_path_sum(build([-3])), max_path_sum(build([-2, -1]))) # -3 -1
print(max_path_sum(build([5, 4, 8, 11, None, 13, 4, 7, 2, None, None, None, 1]))) # 48
Walkthrough: [-10, 9, 20, None, None, 15, 7]
-10
/ \
9 20
/ \
15 7
Node
Left gain
Right gain
Path bending here
Returned to parent
9
0
0
9
9
15
0
0
15
15
7
0
0
7
7
20
15
7
42
20 + 15 = 35
−10
9
35
−10 + 9 + 35 = 34
25
The best path is 15 → 20 → 7 = 42; it does not include the root.
Two Different Quantities
Quantity
Formula
Why
Returned gain
val + max(left, right)
A parent can extend the path through only one child branch, or it would stop being a path
Candidate answer
val + left + right
A path may bend at this node and use both branches, but then it cannot continue upward
Clamping each gain at 0 means “do not extend into a branch that lowers the sum”.
Complexity
Value
Time
O(n): each node processed once
Space
O(h) call stack: O(log n) balanced, O(n) skewed
Edge Cases
All values negative: the answer is the largest single value (−1 for [-2, -1]). This is why best starts at -inf, not 0, and why the node’s own value is always included.
Single node: its value.
Very deep trees: convert to an iterative post-order to avoid recursion limits.
Large values: Python integers do not overflow; in Java or C++, use long if sums can exceed 32 bits.
Related Variants
Variant
Change
Root-to-leaf maximum sum
Return val + max(left, right) without clamping, and require reaching a leaf
Path must start at the root
Only the returned gain at the root matters
Return the path itself
Store the bending node and best branches, then rebuild
Leaf-to-leaf maximum
Do not clamp gains, and update the answer only at nodes that have both children
Common Pitfalls
Initialising the answer to 0, which is wrong when every value is negative.
Returning val + left + right to the parent, which builds “paths” that fork.
Forgetting to clamp negative branches.
Interview Tips
Separate the value returned upward from the candidate answer; this distinction is the core of the problem.
Walk through the -10 example and an all-negative example.
This pattern (return a one-sided best, update a global with a two-sided best) also solves diameter and longest univalue path.
64
Discuss the problem of Serializing and Deserializing a Binary Tree.
KnownRevise
Serialization turns a binary tree into a flat string or byte sequence so it can be stored, sent over a network or cached; deserialization rebuilds the identical tree from it. A traversal alone is not enough: pre-order values without markers can describe many different shapes. The standard fix is to record missing children explicitly (here #). A pre-order traversal with null markers then describes exactly one tree, and both directions run in O(n) time and space. Level order with null markers (the format coding platforms display) works too.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def level_order(root: Node | None) -> list[int]:
out, queue = [], deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.val)
queue.extend(c for c in (node.left, node.right) if c)
return out
def serialize(root: Node | None) -> str:
"""Pre-order with '#' for missing children, e.g. '1,2,#,#,3,4,#,#,5,#,#'."""
out, stack = [], [root]
while stack:
node = stack.pop()
if node is None:
out.append("#")
continue
out.append(str(node.val))
stack.append(node.right) # pushed first, so the left side is written first
stack.append(node.left)
return ",".join(out)
def deserialize(data: str) -> Node | None:
"""Rebuild from the pre-order string in O(n), without recursion."""
tokens = iter(data.split(","))
first = next(tokens)
if first == "#":
return None
root = Node(int(first))
stack = [(root, "left")] # slots still waiting for a child
for token in tokens:
parent, side = stack.pop()
child = None if token == "#" else Node(int(token))
setattr(parent, side, child)
if side == "left":
stack.append((parent, "right"))
if child:
stack.append((child, "left"))
return root
tree = build([1, 2, 3, None, None, 4, 5])
data = serialize(tree)
print(data) # 1,2,#,#,3,4,#,#,5,#,#
print(level_order(deserialize(data))) # [1, 2, 3, 4, 5]
print(serialize(None), deserialize("#")) # # None
print(serialize(deserialize("-7,#,8,#,#"))) # -7,#,8,#,#
Both functions are iterative, so very deep trees do not hit recursion limits.
Walkthrough
1
/ \
2 3
/ \
4 5
Serialize (pre-order): 1, left 2, its two missing children #,#, then 3, 4,#,#, 5,#,#, which gives 1,2,#,#,3,4,#,#,5,#,#.
Deserialize keeps a stack of child slots still waiting to be filled:
Token
Slot filled
Slots pushed
1
becomes root
1.left
2
1.left
1.right, 2.left
#
2.left = None
2.right
#
2.right = None
none
3
1.right
3.left
4
3.left
3.right, 4.left
#, #
4’s children
none
5
3.right
5.left
#, #
5’s children
none
Why Markers Are Needed
Pre-order 1, 2, 3 alone could be 2 and 3 both on the left, a root with two children, or several other shapes. Without markers, you need two traversals (for example in-order plus pre-order) and unique values. Markers remove both requirements.
Format Choices
Format
Size
Notes
Pre-order with null markers
About 2n + 1 tokens
Simple, streams well, rebuilds in one pass
Level order with null markers
Similar; trailing nulls can be trimmed
Matches how coding platforms print trees
Pre-order + in-order
2n values
Needs unique values
BST: pre-order only
n values
Bounds recover the shape, no markers needed
Binary encoding (structure bits + values)
About 2 bits per node + values
Compact for storage
JSON nested objects
Large
Human-readable, schema-friendly
Complexity
Time
Space
Serialize
O(n)
O(n) output, O(h) stack
Deserialize
O(n)
O(n) nodes, O(h) pending slots
Edge Cases
Empty tree:"#".
Negative or multi-digit values: splitting on a delimiter handles them (-7,#,8,#,#).
Values containing the delimiter (strings with commas): escape them, add length prefixes, or use JSON.
Malformed input: validate token counts; a well-formed string has exactly one more # than values.
Very large trees: stream tokens instead of building one large string.
Real Uses
Saving tree-shaped state (decision trees, scene graphs, game trees) to disk.
Sending trees between services or caching them (e.g., in Redis).
Test fixtures and reproducible bug reports.
Merkle trees and file-system snapshots, which serialize nodes and their hashes.
Common Pitfalls
Omitting null markers and assuming one traversal is enough.
Using recursion for both directions on deep trees.
Ambiguous delimiters or locale-dependent number formatting.
Interview Tips
State the format first (pre-order with # for null) and explain why it is unambiguous.
Mention that a BST needs no markers.
Discuss versioning and escaping if the format will be stored long-term.
65
Solve the Vertical Order Traversal of a Binary Tree.
KnownRevise
Vertical order traversal groups nodes into columns. The root is in column 0, a left child is one column to the left (col − 1), and a right child is one to the right (col + 1). The output lists columns left to right, and inside each column the nodes run top to bottom. Problems differ on how to order two nodes in the same row and column: the strict version sorts them by value, while the common BFS version keeps left-to-right order. Record (row, col, value) for every node, group by column, and sort. This takes O(n log n) time.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
from collections import defaultdict, deque
def vertical_order(root: Node | None) -> list[list[int]]:
"""Columns left to right; inside a column, top to bottom, ties by value."""
cells = defaultdict(list) # column -> [(row, value)]
queue = deque([(root, 0, 0)] if root else [])
while queue:
node, row, col = queue.popleft()
cells[col].append((row, node.val))
if node.left:
queue.append((node.left, row + 1, col - 1))
if node.right:
queue.append((node.right, row + 1, col + 1))
return [[val for _, val in sorted(cells[col])] for col in sorted(cells)]
def vertical_order_bfs(root: Node | None) -> list[list[int]]:
"""Common variant: same row and column keep BFS (left-to-right) order."""
columns = defaultdict(list)
queue = deque([(root, 0)] if root else [])
while queue:
node, col = queue.popleft()
columns[col].append(node.val)
if node.left:
queue.append((node.left, col - 1))
if node.right:
queue.append((node.right, col + 1))
return [columns[col] for col in sorted(columns)]
tree = build([1, 2, 3, 4, 6, 5, 7])
print(vertical_order(tree)) # [[4], [2], [1, 5, 6], [3], [7]]
print(vertical_order_bfs(tree)) # [[4], [2], [1, 6, 5], [3], [7]]
print(vertical_order(None)) # []
Nodes 6 and 5 share row 2 and column 0, so the two variants differ only there: the strict version sorts by value, and the BFS version keeps the order it met them (6 is under node 2, which BFS reaches first).
Complexity
Variant
Time
Space
Strict (sort by row, then value)
O(n log n)
O(n)
BFS order, columns sorted at the end
O(n + c log c), where c is the number of columns
O(n)
BFS order with min and max column tracked
O(n): columns are a contiguous range, so no sort is needed
O(n)
Why BFS for the Simpler Variant
DFS reaches a deeper left-side node before a shallower right-side node in the same column, which breaks top-to-bottom order. BFS processes rows in order, so each column’s list is already sorted by row. In the strict variant, the explicit sort by (row, value) makes the traversal order irrelevant.
Related Views
Problem
Rule
Top view
First node seen in each column (BFS)
Bottom view
Last node seen in each column (BFS)
Left or right view
First or last node in each row
Diagonal traversal
Group by col − row or by the number of left turns
Column sums
Sum values per column instead of listing them
Edge Cases
Empty tree:[].
Skewed trees: n columns of one node each (a left chain gives columns −(n−1) to 0).
Duplicate values in the same cell: both kept; sorting by value keeps them adjacent.
Wide trees: column indexes can be negative, so use a dictionary or offset by the minimum column.
Common Pitfalls
Using DFS without recording the row, then listing a column out of top-to-bottom order.
Ignoring the same-cell tie-break the problem asks for.
Indexing a list with negative column numbers.
Interview Tips
Ask how ties in the same row and column should be ordered; this decides between the two versions.
Explain (row, col) coordinates, then the group-and-sort step.
Mention top and bottom views as quick follow-ups with the same coordinate idea.
66
Implement Zigzag (Spiral) Level Order Traversal of a Binary Tree.
KnownRevise
Zigzag (spiral) level order visits the tree level by level like BFS, but alternates direction: the root level left to right, the next level right to left, and so on. The simplest method runs a normal BFS and builds each level’s list in a deque: append to the right on left-to-right levels and to the left on reversed levels. The order of visiting nodes never changes. A classic alternative uses two stacks, which reverse the order naturally. Both take O(n) time and O(w) extra space, where w is the widest level.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
from collections import deque
def zigzag_level_order(root: Node | None) -> list[list[int]]:
"""Level order that alternates left-to-right and right-to-left."""
result, queue, left_to_right = [], deque([root] if root else []), True
while queue:
level = deque()
for _ in range(len(queue)):
node = queue.popleft()
if left_to_right:
level.append(node.val)
else:
level.appendleft(node.val) # O(1) reverse as we go
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
result.append(list(level))
left_to_right = not left_to_right
return result
def zigzag_two_stacks(root: Node | None) -> list[int]:
"""Classic two-stack version: prints a single spiral sequence."""
out, current, following, left_to_right = [], [root] if root else [], [], True
while current:
node = current.pop()
out.append(node.val)
children = (node.left, node.right) if left_to_right else (node.right, node.left)
following.extend(c for c in children if c)
if not current:
current, following, left_to_right = following, [], not left_to_right
return out
tree = build([3, 9, 20, 1, 2, 15, 7])
print(zigzag_level_order(tree)) # [[3], [20, 9], [1, 2, 15, 7]]
print(zigzag_two_stacks(tree)) # [3, 20, 9, 1, 2, 15, 7]
print(zigzag_level_order(None)) # []
Walkthrough
3
/ \
9 20
/ \ / \
1 2 15 7
Level
BFS order
Direction
Output
0
3
left to right
[3]
1
9, 20
right to left (appendleft)
[20, 9]
2
1, 2, 15, 7
left to right
[1, 2, 15, 7]
Two stacks: pop from current; on left-to-right levels, push children left then right onto following, so the next level pops right first. Swap the stacks and flip the direction when current empties.
Complexity
Method
Time
Extra space
BFS + deque per level
O(n)
O(w) queue plus the level
BFS + reverse every other level
O(n): each value is reversed once
O(w)
Two stacks
O(n)
O(w)
DFS by depth, inserting at the front on odd levels
O(n) with deques
O(h) recursion + output
Choosing a Method
Deque per level: the clearest, and the easiest to explain.
Reverse odd levels: the shortest code, and also O(n).
Two stacks: a common textbook answer that produces a single spiral sequence; slightly trickier to get right.
Edge Cases
Empty tree:[].
Single node:[[root]].
Missing children: skipped; positions are not padded with nulls.
Skewed tree: every level has one node, so the direction does not change the output.
Common Pitfalls
Changing the order in which children are queued in BFS instead of the order of the output: this scrambles deeper levels.
Forgetting to flip the direction after each level.
In the two-stack version, pushing children in the wrong order for the current direction.
Using list.insert(0, x), which is O(k) per insert; a deque’s appendleft is O(1).
Related Problems
Problem
Change
Level order
No direction flip
Bottom-up level order
Reverse the list of levels at the end
Right side view
Last value of each level
Level averages or maxima
Aggregate each level
Interview Tips
Say clearly that the traversal order stays BFS; only the output order alternates.
Write the deque version; mention the two-stack version if asked for one without per-level lists.
Test with a three-level tree to show the direction flip.
67
How do you count the nodes with a given value in a binary tree?
KnownRevise
To count the nodes that hold a given value in a general binary tree, visit every node and add 1 whenever its value matches. Any traversal works (DFS with a stack, BFS with a queue, or recursion), and it costs O(n) time, because nothing about a general tree tells you where the value might be. When the tree is a BST with a consistent duplicate rule (for example, duplicates always go right), you can skip subtrees that cannot contain the target. Then only the search path and the run of equal keys are visited, in O(h + k) for k matches.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def count_value(root: Node | None, target: int) -> int:
"""Count nodes equal to target in any binary tree: O(n) time."""
count, stack = 0, [root] if root else []
while stack:
node = stack.pop()
count += node.val == target
stack.extend(c for c in (node.left, node.right) if c)
return count
def count_value_bst(root: Node | None, target: int) -> int:
"""In a BST with duplicates sent right, skip subtrees that cannot match."""
count, stack = 0, [root] if root else []
while stack:
node = stack.pop()
if node.val == target:
count += 1
if target < node.val and node.left:
stack.append(node.left)
if target >= node.val and node.right:
stack.append(node.right)
return count
tree = build([5, 3, 5, 5, 1, None, 5])
print(count_value(tree, 5), count_value(tree, 9)) # 4 0
bst = None
def insert(root, val):
if root is None:
return Node(val)
if val < root.val:
root.left = insert(root.left, val)
else:
root.right = insert(root.right, val) # duplicates go right
return root
for v in [8, 3, 10, 8, 1, 8, 12]:
bst = insert(bst, v)
print(count_value_bst(bst, 8), count_value(bst, 8)) # 3 3
Walkthrough: General Tree, target 5
5
/ \
3 5
/ \ \
5 1 5
Visited
Matches?
Count
5 (root)
yes
1
5 (right child)
yes
2
5 (its right)
yes
3
3
no
3
1
no
3
5 (under 3)
yes
4
All 6 nodes are visited; the value 5 can appear anywhere, even under the 3.
Walkthrough: BST, target 8
Inserting 8, 3, 10, 8, 1, 8, 12 with duplicates going right puts the 8s on one path: 8 → right 10 → left 8 → right 8. The BST count visits the root 8, moves right (8 ≥ 8) to 10, left (8 < 10) to the second 8, then right (8 ≥ 8) to the third. It never visits 3, 1 or 12.
Complexity
Tree
Time
Space
General binary tree
O(n)
O(h) for DFS, O(w) for BFS
BST, duplicates on one side
O(h + k)
O(h)
BST, each node storing a count field
O(h): one search
O(h) or O(1) iterative
Many queries on a static tree
O(n) once to build a hash map of counts, then O(1) per query
O(distinct values)
Design Choices for Duplicates in BSTs
Rule
Effect
Duplicates always go right (or always left)
Equal keys lie along one path; counting follows it
Count field per node (val, count)
One node per distinct key; insert increments count
No duplicates allowed
Count is 0 or 1
The count field is usually the best design: the tree stays shorter and counting is a single search.
Edge Cases
Empty tree: 0.
Value not present: 0 after a full traversal (general tree) or one failed search (BST).
Floating-point values: compare with a tolerance (math.isclose) rather than ==.
Deep trees: the iterative stack avoids recursion limits.
Unknown duplicate rule in a “BST”: fall back to the O(n) traversal; pruning would miss matches.
Common Pitfalls
Stopping at the first match, as you would in a search.
Applying BST pruning to a general binary tree.
In BSTs, pruning with the wrong comparison and missing duplicates on the side where they were inserted.
Interview Tips
Ask: “Is it a BST, and how are duplicates stored?” That decides between O(n) and O(h + k).
Mention a hash map of counts if many queries will be asked on the same tree.
A few lines of iterative DFS are enough for the general case.
68
Solve the problem of finding the Kth Smallest Element in a BST.
KnownRevise
An in-order traversal of a BST visits keys in ascending order, so the kth smallest element is the kth node visited in order. An iterative in-order walk with a stack can stop as soon as it reaches the kth node, costing O(h + k) time and O(h) space. If the tree is queried often or changes frequently, store a subtree size in each node (an order-statistic tree). Each query then picks a direction at every level using the left subtree’s size, in O(h) time, which is O(log n) on a balanced tree.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def kth_smallest(root: Node | None, k: int) -> int:
"""Iterative in-order walk that stops at the kth node: O(h + k) time."""
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
k -= 1
if k == 0:
return node.val
node = node.right
raise ValueError("k is larger than the number of nodes")
@dataclass
class SizedNode:
val: int
left: "SizedNode | None" = None
right: "SizedNode | None" = None
size: int = 1 # nodes in this subtree
def kth_with_sizes(root: SizedNode, k: int) -> int:
"""With subtree sizes kept up to date, each query is O(h)."""
node = root
while node:
left_size = node.left.size if node.left else 0
if k <= left_size:
node = node.left
elif k == left_size + 1:
return node.val
else:
k -= left_size + 1
node = node.right
raise ValueError("k is larger than the number of nodes")
def sized_insert(root, val):
if root is None:
return SizedNode(val)
root.size += 1
if val < root.val:
root.left = sized_insert(root.left, val)
else:
root.right = sized_insert(root.right, val)
return root
bst = build([5, 3, 6, 2, 4, None, None, 1])
print([kth_smallest(bst, k) for k in (1, 3, 6)]) # [1, 3, 6]
sized = None
for v in [5, 3, 6, 2, 4, 1]:
sized = sized_insert(sized, v)
print(kth_with_sizes(sized, 3), sized.size) # 3 6
Walkthrough: In-Order, k = 3
5
/ \
3 6
/ \
2 4
/
1
Step
Stack after pushing lefts
Pop
k after
1
5, 3, 2, 1
1
2
2
5, 3, 2
2
1
3
5, 3
3
0, so return 3
Nodes 4, 5 and 6 are never visited.
Walkthrough: Subtree Sizes, k = 3
At 5, the left subtree has size 4, and 3 ≤ 4, so go left. At 3, the left subtree (2, 1) has size 2, and k = 3 = 2 + 1, so return 3.
Complexity
Method
Query time
Space
Updates
Iterative in-order, early stop
O(h + k)
O(h)
No extra work
Recursive in-order with a counter
O(h + k)
O(h) call stack
No extra work
Collect all values in order, index
O(n)
O(n)
Wasteful
Subtree sizes (order-statistic tree)
O(h)
O(n) size fields
Update sizes on insert, delete and rotation
Morris in-order traversal
O(n) worst case
O(1)
Temporarily changes pointers
Which One to Use
One query: the iterative in-order walk; it is simple and stops early.
Many queries with frequent inserts and deletes: subtree sizes on a balanced tree for O(log n) per operation. Libraries offer this, such as GNU __gnu_pbds::tree with find_by_order in C++.
Memory-constrained: Morris traversal, if temporarily modifying the tree is acceptable.
kth largest: do a reverse in-order walk (right, node, left), or ask for the (n − k + 1)th smallest.
Edge Cases
k < 1 or k > n: raise an error (as here) or return None; agree on this with the interviewer.
Duplicates: with duplicates kept on one side, they appear consecutively in order and count separately.
Skewed tree: h = n, so both methods degrade to O(n); balancing fixes this.
Concurrent updates: subtree sizes must be updated in the same transaction or lock as the structural change.
Common Pitfalls
Using a recursive counter without a way to stop early, which visits all n nodes.
Forgetting to update subtree sizes during rotations in a self-balancing tree.
Sorting all values (O(n log n)) when the tree is already ordered.
Interview Tips
Start with “in-order is sorted”, then write the iterative version with an early return.
For the common follow-up, “the BST is modified often and kth is queried often”, answer with subtree sizes on a balanced tree.
Mention kth largest via reverse in-order.
69
Discuss the Subtree with Maximum Average problem and how to approach it.
KnownRevise
The subtree with maximum average problem asks: among all subtrees (a node together with all its descendants), which one has the largest average value, that is, sum ÷ node count? Computing each subtree’s sum and size from scratch is O(n²). The efficient approach is a single post-order traversal: each node gets its subtree sum and count from its children, adds itself, and compares sum / count with the best so far. This runs in O(n) time. Comparing total × best_count with best_total × count avoids floating-point error.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def max_average_subtree(root: Node) -> tuple[float, int]:
"""Best (average, subtree root value) over all subtrees, in one post-order pass."""
best_total, best_count, best_root = None, 1, None
stack, totals = [(root, False)], {} # totals: id(node) -> (sum, count)
while stack:
node, children_done = stack.pop()
if not children_done:
stack.append((node, True))
stack.extend((c, False) for c in (node.left, node.right) if c)
continue
total, count = node.val, 1
for child in (node.left, node.right):
if child:
child_total, child_count = totals.pop(id(child))
total, count = total + child_total, count + child_count
totals[id(node)] = (total, count)
# Compare total/count > best_total/best_count without floating-point division.
if best_total is None or total * best_count > best_total * count:
best_total, best_count, best_root = total, count, node.val
return best_total / best_count, best_root
print(max_average_subtree(build([5, 6, 1]))) # (6.0, 6)
print(max_average_subtree(build([2, 4, 6, 1, 7, None, 0]))) # (7.0, 7)
print(max_average_subtree(build([-5, -2, -9]))) # (-2.0, -2)
print(max_average_subtree(build([10, 2, 3]))) # (5.0, 10) whole tree: 15 / 3
The traversal is an iterative post-order: each node is pushed twice, once to schedule its children and once to combine their results. That avoids recursion limits on deep trees.
Walkthrough: [2, 4, 6, 1, 7, None, 0]
2
/ \
4 6
/ \ \
1 7 0
Subtree root
Sum
Count
Average
1
1
1
1.0
7
7
1
7.0
4
12
3
4.0
0
0
1
0.0
6
6
2
3.0
2
20
6
3.33
The best subtree is the single leaf 7. In [10, 2, 3], the whole tree (average 5) beats either leaf.
Complexity
Approach
Time
Space
Recompute each subtree separately
O(n²) on a skewed tree
O(h)
One post-order pass returning (sum, count)
O(n)
O(h)
Variations
Variant
Change
N-ary tree (common in interviews)
Sum over all children instead of two
Only subtrees with at least 2 nodes (leaves excluded)
Skip leaves when updating the best
Return the node itself
Store the node, not its value
Maximum subtree sum
Track sums only
Ties
Decide: first found, smallest root value, or any
Because a single large leaf often wins, many versions of the problem exclude leaves; ask which version is meant.
Edge Cases
Single node: its own value.
All negative values: the least negative subtree wins (−2 in the example); initialise the best as “none yet”, not 0.
Ties: this code keeps the first one found in post-order (strict >).
Large sums: Python integers do not overflow; in Java or C++ use long.
Floating-point averages: cross-multiplication keeps comparisons exact for integers.
Common Pitfalls
Confusing subtree (a node and all its descendants) with any connected subgraph, which is a much harder problem.
Recomputing sums at every node.
Starting the best average at 0, which is wrong for all-negative trees.
Integer division in languages where / truncates.
Interview Tips
Name the pattern: “post-order, return aggregates (sum, count) to the parent”. The same pattern solves subtree sums, balanced checks and the diameter.
Clarify whether leaves count and what to return (value, node or average).
Mention exact comparison by cross-multiplication.
70
Convert a Binary Search Tree to a Sorted Doubly Linked List.
KnownRevise
To convert a BST into a sorted doubly linked list in place, reuse each node’s pointers: left becomes prev and right becomes next. An in-order traversal visits nodes in sorted order, so keep a reference to the previously visited node and link it to the current one (prev.right = node, node.left = prev). The first node visited (the smallest key) is the head. This takes O(n) time and O(h) space for the traversal stack, with no new nodes. A circular variant also links the tail back to the head.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def bst_to_sorted_dll(root: Node | None) -> Node | None:
"""In place: left = previous, right = next. Returns the head (smallest)."""
head = prev = None
stack, node = [], root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
if prev:
prev.right, node.left = node, prev
else:
head = node
prev, node = node, node.right
return head
def forward(head: Node | None) -> list[int]:
out = []
while head:
out.append(head.val)
head = head.right
return out
bst = build([4, 2, 5, 1, 3])
head = bst_to_sorted_dll(bst)
print(forward(head)) # [1, 2, 3, 4, 5]
tail = head
while tail.right:
tail = tail.right
back = []
while tail:
back.append(tail.val)
tail = tail.left
print(back) # [5, 4, 3, 2, 1]
print(bst_to_sorted_dll(None)) # None
Changing a node’s right pointer is safe here because the stack walk has already moved past it: node.right is read in the same step that moves on, and prev.right is overwritten only after prev‘s right subtree is finished.
Circular Version
After the loop, prev is the tail. Add head.left, prev.right = prev, head to make it circular, which is the form many interview problems ask for.
Complexity
Value
Time
O(n): each node visited once
Space
O(h) stack: O(log n) balanced, O(n) skewed; no new nodes
Morris-style threading
O(1) extra space, O(n) time, more complex
Alternative Approaches
Approach
Notes
Iterative in-order with prev (above)
Clear and safe for deep trees
Recursive in-order with prev as a nonlocal
Shortest code; recursion depth = height
Divide and conquer: convert left and right subtrees, then join left list + node + right list
Elegant with circular lists; O(n)
Collect nodes into an array, then link
O(n) extra space, simplest to reason about
Edge Cases
Empty tree: returns None.
Single node: head is that node, with left and right both None (or pointing to itself in the circular version).
Skewed trees: already list-like; recursion would be deep, so the iterative version is safer.
The original tree is destroyed: callers must not use it as a BST afterward. Copy it first if both are needed.
Uses
Merging two BSTs: convert both to sorted lists, merge them in O(n + m), then rebuild a balanced BST from the merged list.
Ordered iteration in both directions without a stack.
Range scans from a found node in either direction.
Common Pitfalls
Forgetting to set head on the first visit.
Using pre-order or post-order, which do not produce sorted order.
Leaving the tail’s right (or the head’s left) set incorrectly in the circular variant.
Interview Tips
State the key idea: in-order plus a prev pointer, rewiring left and right.
Ask whether the list should be circular and whether modifying the tree is allowed.
Mention the merge two BSTs application.
71
How do you construct a Binary Tree from Inorder and Preorder traversals?
KnownRevise
Preorder lists the root first, then the left subtree, then the right subtree; inorder lists the left subtree, then the root, then the right subtree. So the first preorder value is the root, and its position in the inorder list splits the remaining values into the left subtree (everything before it) and the right subtree (everything after it). Apply the same rule recursively. A hash map from value to inorder index makes each split O(1), so the whole build runs in O(n). This works when all values are unique; with duplicates, the two traversals can describe more than one tree.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def level_order(root: Node | None) -> list[int]:
out, queue = [], deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.val)
queue.extend(c for c in (node.left, node.right) if c)
return out
def build_from_traversals(preorder: list[int], inorder: list[int]) -> Node | None:
"""Rebuild a tree with unique values from its preorder and inorder sequences."""
if len(preorder) != len(inorder):
raise ValueError("traversals have different lengths")
position = {val: i for i, val in enumerate(inorder)} # O(1) root lookup
next_root = 0
def build_range(lo: int, hi: int) -> Node | None:
"""Build the subtree whose inorder values are inorder[lo:hi]."""
nonlocal next_root
if lo >= hi:
return None
val = preorder[next_root]
next_root += 1
mid = position[val]
node = Node(val)
node.left = build_range(lo, mid) # preorder lists the whole left subtree first
node.right = build_range(mid + 1, hi)
return node
return build_range(0, len(inorder))
root = build_from_traversals([3, 9, 20, 15, 7], [9, 3, 15, 20, 7])
print(level_order(root)) # [3, 9, 20, 15, 7]
print(root.right.left.val, root.right.right.val) # 15 7
print(build_from_traversals([], [])) # None
print(level_order(build_from_traversals([1, 2, 3], [3, 2, 1]))) # [1, 2, 3] (a left chain)
next_root simply moves forward through the preorder list, because preorder visits each root just before building its left subtree and then its right subtree, which is the same order the recursion uses.
Complexity
Approach
Time
Space
Hash map of inorder positions + index pointer (above)
O(n)
O(n) map + O(h) recursion
Linear search for the root in each call
O(n²) worst case (skewed tree)
O(h)
Slicing lists in each call
O(n²) because slices copy
O(n²) total copies
Which Traversal Pairs Work
Pair
Unique tree?
Preorder + inorder
Yes (unique values)
Postorder + inorder
Yes: build from the end of postorder, right subtree first
Level order + inorder
Yes, though less efficient
Preorder + postorder
Only for full binary trees (every node has 0 or 2 children)
Preorder alone
Only for a BST (use value bounds) or with null markers
Edge Cases
Empty input: returns None.
Skewed tree: recursion depth equals n. Python’s limit (about 1,000) needs an iterative stack-based version for large skewed inputs.
Duplicates: not supported; position would keep only the last index.
Invalid input (the two lists are not traversals of the same tree): a KeyError or a wrong tree. Check that both lists have the same set of values first.
Common Pitfalls
Building the right subtree before the left with preorder: next_root would then pick the wrong roots.
Slicing arrays in every call, which makes the build quadratic.
Searching linearly for the root’s inorder position.
Interview Tips
State the two facts: preorder gives roots; inorder splits left from right.
Mention the hash map for O(n) and the moving index instead of slices.
Expect the follow-up with postorder + inorder: take roots from the end and build the right subtree first.
72
Write a function to Check if a Binary Tree is Full or not.
KnownRevise
A full binary tree (also called a proper or strictly binary tree) is one in which every node has either 0 or 2 children, never exactly one. To check it, visit every node and fail as soon as one node has exactly one child, which is easy to test as (left is None) != (right is None). An empty tree and a single node both count as full. The check is O(n) in the worst case and stops at the first violation.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def is_full(root: Node | None) -> bool:
"""Full (proper) binary tree: every node has 0 or 2 children."""
stack = [root] if root else []
while stack:
node = stack.pop()
if (node.left is None) != (node.right is None):
return False # exactly one child
if node.left:
stack.extend((node.left, node.right))
return True
print(is_full(build([1, 2, 3, 4, 5]))) # True
print(is_full(build([1, 2, 3, 4]))) # False (2 has only a left child)
print(is_full(build([1, 2, 3, None, None, 6, 7]))) # True
print(is_full(None), is_full(build([1]))) # True True
The stack-based traversal avoids recursion limits on deep trees. A recursive version is one line: root is None or ((root.left is None) == (root.right is None) and is_full(root.left) and is_full(root.right)).
Walkthrough
Full Not full
1 1
/ \ / \
2 3 2 3
/ \ /
4 5 4 <- node 2 has only one child
Node (right tree)
Left
Right
Exactly one child?
1
2
3
no
3
None
None
no
2
4
None
yes, so return False
Full, Complete, Perfect and Balanced
Term
Definition
Example [1, 2, 3, 4]
Full
Every node has 0 or 2 children
No
Complete
All levels filled except possibly the last, which is filled from the left
Yes
Perfect
Full, and all leaves at the same depth (2^(h+1) − 1 nodes)
No
Balanced (height-balanced)
At every node, subtree heights differ by at most 1
Yes
These are independent properties: a tree can be full but not complete, or complete but not full.
Useful Facts About Full Trees
Leaves = internal nodes + 1. With i internal nodes, there are 2i + 1 nodes in total.
So a full binary tree always has an odd number of nodes, which allows a quick O(1) rejection when the count is known and even (and non-zero).
Expression trees with binary operators, Huffman trees and tournament brackets are full by construction.
Complexity
Value
Time
O(n) worst case; stops early at the first node with one child
Space
O(h) stack for DFS (O(w) if you use BFS)
Edge Cases
Empty tree: full by the usual convention; confirm the convention with the interviewer.
Single node: full (0 children).
Skewed tree: fails at the root’s first child, since each internal node has exactly one child.
Deep trees: the iterative version is safe; the one-line recursion is not.
Common Pitfalls
Confusing full with complete or perfect.
Checking only the root.
Writing if node.left and node.right and forgetting to reject the one-child case explicitly.
Interview Tips
Define the term first, since definitions differ between textbooks (“full” sometimes means “perfect”).
Use the XOR-style test (left is None) != (right is None).
Mention the property leaves = internal + 1 as a bonus.
73
How do you connect nodes at the same level in a binary tree?
KnownRevise
Connecting nodes at the same level means filling a next pointer in every node so it points to the node immediately to its right on the same level, or None for the last node of a level. The easy approach is a BFS that links each node to the one after it in the queue, in O(n) time and O(w) space. A better approach uses O(1) extra space: walk the current level through the next pointers that are already set, and build the next level’s links behind a dummy head. This version works for any binary tree, not only perfect ones.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
@dataclass
class LinkedNode:
val: int
left: "LinkedNode | None" = None
right: "LinkedNode | None" = None
next: "LinkedNode | None" = None # the node to the right on the same level
def connect(root: LinkedNode | None) -> LinkedNode | None:
"""Fill every next pointer in O(n) time and O(1) extra space, for any binary tree."""
level_start = root
while level_start:
dummy = tail = LinkedNode(0) # builds the next level as a linked list
node = level_start
while node: # walk the current level using next pointers
for child in (node.left, node.right):
if child:
tail.next = child
tail = child
node = node.next
level_start = dummy.next
return root
def to_linked(node: Node | None) -> LinkedNode | None:
if node is None:
return None
return LinkedNode(node.val, to_linked(node.left), to_linked(node.right))
def levels_via_next(root: LinkedNode | None) -> list[list[int]]:
"""Read each level by following next pointers only."""
out, start = [], root
while start:
row, node, below = [], start, None
while node:
row.append(node.val)
below = below or node.left or node.right # leftmost node of the next level
node = node.next
out.append(row)
start = below
return out
tree = connect(to_linked(build([1, 2, 3, 4, 5, None, 7])))
print(levels_via_next(tree)) # [[1], [2, 3], [4, 5, 7]]
print(tree.left.right.next.val, tree.right.next) # 7 None
The gap where 3 has no left child is handled naturally: tail simply links 5 to 7.
Complexity
Approach
Time
Extra space
BFS with a queue
O(n)
O(w), up to about n/2
Level walk with next + dummy head (above)
O(n)
O(1)
Recursion for perfect trees (node.left.next = node.right, node.right.next = node.next.left)
O(n)
O(h) call stack
Why the Dummy Head Helps
Without it, you need special cases for “first child found on this level” and “previous child”. The dummy node tail always has somewhere to attach the next child, and dummy.next is the leftmost node of the next level, which is where the following pass starts.
Edge Cases
Empty tree: nothing to do.
Missing children anywhere: handled; the perfect-tree shortcut would fail here.
Skewed tree: every level has one node, and every next is None.
Pre-existing next values: the code overwrites each level’s links completely, so stale values are not trusted.
Common Pitfalls
Using the perfect-tree trick on a general tree: node.next.left may not exist, and gaps are skipped incorrectly.
Forgetting to set the last node’s next to None (the dummy approach leaves it None by default).
Starting the next level at level_start.left, which is wrong when the leftmost node has no left child.
Applications
Level-by-level iteration without a queue, for example in memory-constrained embedded code.
Right side view: the last node in each next chain.
Sibling navigation in UI trees and spatial indexes.
Interview Tips
Give the BFS version first, then improve to O(1) space with the dummy-head walk.
Ask whether the tree is perfect; if so, mention the two-line recursive rule.
Trace a tree with a gap (like the missing left child of 3).
74
Solve the problem of finding the number of Islands in a binary matrix.
KnownRevise
In a binary matrix, an island is a group of 1 cells connected horizontally or vertically (diagonals usually do not count). To count islands, scan every cell; when you find an unvisited 1, increase the count and flood-fill its whole island with BFS or DFS, marking each cell visited so it is not counted again. Every cell is processed a constant number of times, so the algorithm runs in O(rows × cols). Union-find is an alternative that also supports adding land cells one at a time. This is a graph problem: each flood fill builds a spanning tree of one island.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from collections import deque
def count_islands(grid: list[list[int]]) -> int:
"""Count groups of 1s connected up, down, left or right (BFS flood fill)."""
rows, cols = len(grid), len(grid[0]) if grid else 0
seen = [[False] * cols for _ in range(rows)]
islands = 0
for r in range(rows):
for c in range(cols):
if grid[r][c] == 1 and not seen[r][c]:
islands += 1
seen[r][c] = True
queue = deque([(r, c)])
while queue:
y, x = queue.popleft()
for ny, nx in ((y + 1, x), (y - 1, x), (y, x + 1), (y, x - 1)):
if 0 <= ny < rows and 0 <= nx < cols and grid[ny][nx] == 1 and not seen[ny][nx]:
seen[ny][nx] = True
queue.append((ny, nx))
return islands
class DisjointSet:
"""Union-find with path halving and union by size."""
def __init__(self, n: int) -> None:
self.parent, self.size = list(range(n)), [1] * n
def find(self, x: int) -> int:
while self.parent[x] != x:
self.parent[x] = self.parent[self.parent[x]]
x = self.parent[x]
return x
def union(self, a: int, b: int) -> bool:
a, b = self.find(a), self.find(b)
if a == b:
return False
if self.size[a] < self.size[b]:
a, b = b, a
self.parent[b], self.size[a] = a, self.size[a] + self.size[b]
return True
def count_islands_union_find(grid: list[list[int]]) -> int:
rows, cols = len(grid), len(grid[0]) if grid else 0
sets, count = DisjointSet(rows * cols), 0
for r in range(rows):
for c in range(cols):
if grid[r][c] != 1:
continue
count += 1
for nr, nc in ((r - 1, c), (r, c - 1)): # merge with land above and to the left
if nr >= 0 and nc >= 0 and grid[nr][nc] == 1 and sets.union(r * cols + c, nr * cols + nc):
count -= 1
return count
grid = [
[1, 1, 0, 0, 0],
[1, 1, 0, 0, 1],
[0, 0, 1, 0, 1],
[0, 0, 0, 1, 1],
]
print(count_islands(grid), count_islands_union_find(grid)) # 3 3
print(count_islands([[1, 0, 1], [0, 1, 0], [1, 0, 1]])) # 5 (diagonals do not connect)
print(count_islands([]), count_islands([[0, 0]])) # 0 0
Walkthrough
1 1 0 0 0 island A: the 2x2 block at the top left
1 1 0 0 1 island B: (1,4), (2,4), (3,4), (3,3)
0 0 1 0 1 island C: (2,2) alone, since its only neighbours of 1 are diagonal
0 0 0 1 1
Scan reaches
Unvisited land?
Action
Count
(0, 0)
yes
BFS marks (0,0), (0,1), (1,0), (1,1)
1
(1, 4)
yes
BFS marks (1,4), (2,4), (3,4), (3,3)
2
(2, 2)
yes
BFS marks only (2,2)
3
other 1s
already visited
skip
3
Complexity
Approach
Time
Extra space
BFS flood fill
O(R·C)
O(R·C) for seen and the queue
Recursive DFS
O(R·C)
O(R·C) call stack in the worst case (a snake-shaped island), which overflows Python’s default limit
Union-find
O(R·C · α(R·C)), effectively linear
O(R·C)
In-place marking (set visited cells to 0)
O(R·C)
O(1) extra besides the queue, but destroys the input
Choosing a Method
One-off count: BFS or iterative DFS.
Land added over time (“number of islands II”): union-find; each new cell unites with its land neighbours, and the count is updated in nearly O(1).
Huge grids that do not fit in memory: process row by row with union-find on two rows at a time.
Edge Cases
Empty grid or all water: 0.
All land: 1.
Diagonal-only neighbours: separate islands under 4-connectivity (the checkerboard example has 5). Use 8 directions if the problem says diagonals connect.
Character grids ("1"/"0"): compare with the right type.
Modifying input: marking with 0 saves memory but changes the caller’s data; ask first.
Common Pitfalls
Marking cells visited when they are popped rather than when they are pushed, which queues cells many times.
Recursive DFS on large grids, which causes a stack overflow.
Swapping rows and columns in bounds checks on non-square grids.
Related Problems
Problem
Change
Max area of an island
Count cells in each flood fill
Number of distinct island shapes
Record each island’s cell offsets relative to its first cell
Surrounded regions
Flood-fill from the border first
Rotting oranges
Multi-source BFS with time levels
Interview Tips
Say: “scan; at each new land cell, count it and flood-fill its island”.
Prefer iterative BFS and explain the recursion risk.
Mention union-find for the dynamic version.
75
Flatten a Binary Tree to a Linked List in place.
KnownRevise
Flattening a binary tree to a linked list in place means rearranging its nodes so they form a chain through the right pointers, in preorder (root, left subtree, right subtree), with every left pointer set to None. An elegant O(1)-extra-space method walks down the right spine: at each node with a left child, find the rightmost node of the left subtree (the last node of that subtree in preorder), attach the node’s original right subtree there, then move the left subtree to the right. Each edge is walked a constant number of times, so the total time is O(n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def flatten(root: Node | None) -> None:
"""Flatten in place into a right-pointing list in preorder; O(n) time, O(1) space."""
node = root
while node:
if node.left:
tail = node.left
while tail.right: # rightmost node of the left subtree
tail = tail.right
tail.right = node.right # attach the old right subtree after it
node.right, node.left = node.left, None
node = node.right
def as_list(root: Node | None) -> list[int]:
out = []
while root:
assert root.left is None
out.append(root.val)
root = root.right
return out
tree = build([1, 2, 5, 3, 4, None, 6])
flatten(tree)
print(as_list(tree)) # [1, 2, 3, 4, 5, 6]
single = build([0])
flatten(single)
print(as_list(single)) # [0]
Each search for a rightmost node walks the right spine of a left subtree. After the rewiring, those nodes are on the main chain, and they are not walked as a “rightmost search” again. So each edge is traversed at most twice in total: once in a search and once by node = node.right.
Complexity
Approach
Time
Extra space
Rightmost-of-left rewiring (above, Morris-like)
O(n)
O(1)
Reverse postorder with a prev pointer (right, left, node)
O(n)
O(h) recursion
Stack-based preorder
O(n)
O(h)
Collect preorder into a list, then relink
O(n)
O(n)
The reverse-postorder version is short: visit right, then left, then set node.right = prev; node.left = None; prev = node.
Edge Cases
Empty tree: nothing happens.
Single node: unchanged.
Already a right chain: the loop just walks it.
Left chain: each step moves one subtree, still O(n) overall.
Deep trees: the O(1)-space loop has no recursion, so depth does not matter.
Common Pitfalls
Forgetting node.left = None, which leaves the result partly tree-shaped.
Attaching the old right subtree to the left child instead of the rightmost node of the left subtree, which breaks preorder.
Using inorder instead of preorder (unless the problem asks for a sorted list from a BST).
Losing the right subtree by overwriting node.right before saving it.
Variants
Variant
Change
Doubly linked list
Also set left to the previous node (see BST → sorted DLL)
Inorder order
Use an inorder walk with prev
Return a new list
Copy nodes instead of rewiring
Interview Tips
Write the stack or reverse-postorder solution first if you are unsure, then mention the O(1)-space rightmost-of-left technique.
Trace the 6-node example to show the preorder result.
Point out that the original tree structure is destroyed.
76
How do you implement a Boundary Traversal of a Binary Tree?
KnownRevise
Boundary traversal lists a binary tree’s outline anticlockwise, starting at the root, in three parts: the left boundary top-down (the path that prefers left children), all leaves from left to right, and the right boundary bottom-up (the path that prefers right children). Leaves are excluded from both boundary paths so that none is printed twice, and the root appears only once. Each part is a simple walk, so the whole traversal is O(n).
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def boundary_traversal(root: Node | None) -> list[int]:
"""Anticlockwise boundary: root, left boundary, leaves left to right, right boundary bottom-up."""
if root is None:
return []
def is_leaf(node: Node) -> bool:
return node.left is None and node.right is None
result = [root.val]
node = root.left # left boundary, top-down, excluding leaves
while node:
if not is_leaf(node):
result.append(node.val)
node = node.left or node.right
stack = [root] if not is_leaf(root) else []
while stack: # leaves, left to right (preorder DFS)
node = stack.pop()
if is_leaf(node):
result.append(node.val)
stack.extend(c for c in (node.right, node.left) if c)
right_side, node = [], root.right # right boundary, collected top-down
while node:
if not is_leaf(node):
right_side.append(node.val)
node = node.right or node.left
return result + right_side[::-1] # added bottom-up
tree = build([1, 2, 3, 4, 5, 6, 7, None, None, 8, 9])
print(boundary_traversal(tree)) # [1, 2, 4, 8, 9, 6, 7, 3]
print(boundary_traversal(build([1, None, 2, 3, 4]))) # [1, 3, 4, 2]
print(boundary_traversal(build([7]))) # [7]
Walkthrough
1
/ \
2 3
/ \ / \
4 5 6 7
/ \
8 9
Part
Rule
Values
Root
always first
1
Left boundary
from root.left, go left if possible, otherwise right; skip leaves
2 (4 is a leaf, so it is skipped here)
Leaves
left to right
4, 8, 9, 6, 7
Right boundary
from root.right, go right if possible, otherwise left; skip leaves; reverse
3
Result: [1, 2, 4, 8, 9, 6, 7, 3].
For the tree 1 → right 2 → (3, 4), the root has no left subtree, so the left boundary is empty, and the output is [1, 3, 4, 2].
Complexity
Part
Time
Left boundary
O(h)
Leaves
O(n)
Right boundary
O(h)
Total
O(n) time, O(h) space for the leaf stack
Definition Details to Confirm
Question
Common answer
Is the root listed if it is a leaf?
Yes, once
If a boundary node has no left child, does the boundary continue right?
Yes (“go left, else right”)
What if the root has no left child?
The left boundary is empty; the root is listed once
Clockwise or anticlockwise?
Usually anticlockwise; clockwise reverses the order of the parts
Interview problems differ on these details, so state the rules before you code.
Edge Cases
Single node:[root].
Only a left chain: left boundary is every non-leaf node, then the single leaf; the right boundary is empty.
Skewed right: root, then the leaf, then the right chain bottom-up.
Deep trees: the code uses loops and an explicit stack, so recursion limits do not apply.
Common Pitfalls
Printing leaves twice because a boundary walk includes them.
Printing the root twice when it is also treated as part of a boundary.
Listing the right boundary top-down instead of bottom-up.
Collecting leaves with level order, which does not give left-to-right leaf order for uneven trees.
Interview Tips
Split the problem into three helper walks and say so before coding.
Clarify the conventions in the table above.
Test a tree whose root has no left child; it is the most common bug.
77
Implement a function to find if a given binary tree is Symmetric or not.
KnownRevise
A binary tree is symmetric when it is a mirror image of itself around a vertical line through the root. In other words, the left subtree is the mirror of the right subtree. To check it, compare nodes in pairs: the two roots of the subtrees must have equal values, the outer children must match (left.left with right.right), and the inner children must match (left.right with right.left). This works recursively or iteratively with a queue of pairs, in O(n) time.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
from collections import deque
def is_symmetric(root: Node | None) -> bool:
"""True if the tree is a mirror image of itself around the root."""
if root is None:
return True
pairs = deque([(root.left, root.right)])
while pairs:
a, b = pairs.popleft()
if a is None and b is None:
continue
if a is None or b is None or a.val != b.val:
return False
pairs.append((a.left, b.right)) # outer pair
pairs.append((a.right, b.left)) # inner pair
return True
def is_symmetric_recursive(root: Node | None) -> bool:
def mirror(a: Node | None, b: Node | None) -> bool:
if a is None or b is None:
return a is b
return a.val == b.val and mirror(a.left, b.right) and mirror(a.right, b.left)
return root is None or mirror(root.left, root.right)
print(is_symmetric(build([1, 2, 2, 3, 4, 4, 3]))) # True
print(is_symmetric(build([1, 2, 2, None, 3, None, 3]))) # False
print(is_symmetric_recursive(build([1, 2, 2, 3, 4, 4, 3]))) # True
print(is_symmetric(None), is_symmetric(build([5]))) # True True
In the right-hand tree, the first pair (2, 2) is fine. Its outer pair is (None, 3): one side is missing, so the tree is not symmetric. The values alone would not reveal this, since both subtrees hold 2 and 3; the shapes differ.
Complexity
Version
Time
Space
Iterative with a queue of pairs
O(n)
O(w) queue
Recursive
O(n)
O(h) call stack
Mirror the left subtree and compare it with the right
O(n)
O(h), but modifies the tree or needs a copy
All versions stop at the first mismatch.
Why Not Compare Traversals?
Comparing the inorder sequence with its reverse fails: [1, 2, 2, 2, None, 2] has the palindromic inorder 2, 2, 1, 2, 2, yet it is not symmetric (both lower 2s are left children). Traversals lose shape information unless you add null markers, and at that point the direct pairwise check is simpler.
Edge Cases
Empty tree: symmetric.
Single node: symmetric.
Same values, different shapes: not symmetric (the right-hand example).
Large or deep trees: use the iterative version to avoid recursion limits.
Related Problems
Problem
Relationship
Same tree
Compare left with left and right with right
Mirror trees
Same pairwise rule applied to two different trees
Invert a tree
Mirroring; a symmetric tree is unchanged by it
Isomorphic trees
Each pair may match straight or swapped
Common Pitfalls
Comparing left.left with right.left (same side) instead of the mirrored side.
Checking only values per level (for example, that each level is a palindrome) without tracking missing children.
Returning True too early when only one of a pair is None.
Interview Tips
Explain the outer pair / inner pair rule, then write the recursive helper mirror(a, b).
Offer the iterative queue version for deep trees.
Trace the asymmetric example to show why shape matters.
78
How do you implement locking and unlocking of nodes in an n-ary tree?
KnownRevise
In the classic tree-locking problem, a node can be locked only if no ancestor and no descendant is already locked, and it can be unlocked only by the user who locked it. The models are hierarchical resources such as folders, organisation units or database objects, where locking a parent must cover its whole subtree. The naive check scans the entire subtree, in O(n). Storing a count of locked descendants in every node makes the descendant check O(1). Ancestors are checked by walking parent pointers, so lock and unlock both run in O(h), where h is the tree’s height.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
class LockingTree:
"""n-ary tree where a node can be locked only if no ancestor or descendant is locked."""
def __init__(self, parent: list[int]) -> None:
self.parent = parent # parent[0] == -1 for the root
self.children: list[list[int]] = [[] for _ in parent]
for node, p in enumerate(parent):
if p >= 0:
self.children[p].append(node)
self.owner: list[int | None] = [None] * len(parent)
self.locked_below = [0] * len(parent) # locked nodes strictly inside each subtree
def _ancestors(self, node: int):
node = self.parent[node]
while node >= 0:
yield node
node = self.parent[node]
def lock(self, node: int, user: int) -> bool:
"""O(h): checks ancestors directly, descendants through locked_below."""
if self.owner[node] is not None or self.locked_below[node]:
return False
if any(self.owner[a] is not None for a in self._ancestors(node)):
return False
self.owner[node] = user
for a in self._ancestors(node):
self.locked_below[a] += 1
return True
def unlock(self, node: int, user: int) -> bool:
"""Only the user who locked the node may unlock it."""
if self.owner[node] != user:
return False
self.owner[node] = None
for a in self._ancestors(node):
self.locked_below[a] -= 1
return True
# 0
# / | \
# 1 2 3
# / \ \
# 4 5 6
tree = LockingTree([-1, 0, 0, 0, 1, 1, 3])
print(tree.lock(4, user=7)) # True
print(tree.lock(1, user=8)) # False: descendant 4 is locked
print(tree.lock(0, user=8)) # False: descendant 4 is locked
print(tree.lock(5, user=8)) # True: sibling subtrees are independent
print(tree.unlock(4, user=8)) # False: user 8 does not own node 4
print(tree.unlock(4, user=7), tree.unlock(5, user=8), tree.lock(1, user=8)) # True True True
How the Counters Work
Event
Updates
lock(4)
owner[4] = 7; locked_below[1] and locked_below[0] each go up by 1
lock(1)
Rejected: locked_below[1] = 1
lock(0)
Rejected: locked_below[0] = 1
unlock(4) by user 8
Rejected: the owner is 7
unlock(4) and unlock(5) by their owners
Counters on 1 and 0 return to 0, so lock(1) now succeeds
Complexity
Operation
Naive
With locked_below counters
lock
O(h) ancestors + O(subtree) descendants
O(h)
unlock
O(1)
O(h) to update ancestors
is_locked
O(1)
O(1)
Space
O(n)
O(n)
For a balanced m-ary tree, h = O(log_m n). For deep, chain-like trees, h can approach n.
The Common “Upgrade” Extension
Many versions add upgrade(node, user): lock the node for the user if it is unlocked, no ancestor is locked, and at least one descendant is locked, and then unlock all its descendants. With the counters, the first three checks are O(h). Unlocking the descendants needs a traversal of the subtree, which is O(subtree size), and each unlocked descendant updates its ancestors’ counters. To keep that cheap, keep a set of locked nodes per subtree, or accept the cost, since upgrades are usually rare.
Concurrency in Real Systems
The code above is single-threaded. In a multi-threaded service:
Protect each lock with one mutex, or use lock coupling down the path.
Databases use intention locks (IS, IX) on ancestors. A transaction that wants to lock a row first places intention locks on the table and page, so a whole-table lock can detect conflicts without scanning rows. This is the same idea as locked_below.
Distributed systems use a coordination service (ZooKeeper, etcd) with hierarchical keys and leases.
Edge Cases
Locking the root: only allowed when nothing in the tree is locked.
Re-locking an already locked node: rejected, even by its owner, unless re-entrant locks are a requirement.
Unlocking a node that is not locked:owner[node] is None, which never equals a user ID, so it is rejected.
Node IDs out of range: validate them first in real code.
Common Pitfalls
Checking only the node’s direct parent or children instead of all ancestors and descendants.
Forgetting to decrement the counters on unlock, so the tree slowly “locks up”.
Allowing any user to unlock.
Interview Tips
Start from the rule (no locked ancestor or descendant), give the naive solution, then add the descendant counter for O(h).
Mention intention locks in databases as the real-world version of the same idea.
Ask whether upgrade is part of the problem.
79
Explain the Morris In-Order Tree Traversal algorithm and its advantages.
KnownRevise
Morris traversal performs an in-order traversal in O(n) time with O(1) extra space, with no stack and no recursion. It works by temporarily threading the tree. Before descending into a node’s left subtree, it makes that subtree’s in-order predecessor (its rightmost node) point back to the node through its empty right pointer. When the traversal later follows that thread back, it knows the left subtree is finished, removes the thread, outputs the node and moves right. When it ends, the tree is exactly as it was.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def morris_inorder(root: Node | None) -> list[int]:
"""In-order traversal with O(1) extra space, using temporary threads."""
out, node = [], root
while node:
if node.left is None:
out.append(node.val)
node = node.right
continue
pred = node.left
while pred.right and pred.right is not node: # in-order predecessor
pred = pred.right
if pred.right is None:
pred.right = node # create a thread back to node, then go left
node = node.left
else:
pred.right = None # second visit: remove the thread
out.append(node.val)
node = node.right
return out
def shape(root: Node | None) -> tuple:
return () if root is None else (root.val, shape(root.left), shape(root.right))
tree = build([4, 2, 6, 1, 3, 5, 7])
before = shape(tree)
print(morris_inorder(tree)) # [1, 2, 3, 4, 5, 6, 7]
print(shape(tree) == before) # True: every thread was removed
print(morris_inorder(build([1, None, 2, 3]))) # [1, 3, 2]
Walkthrough
4
/ \
2 6
/ \ / \
1 3 5 7
Step
Node
Action
1
4
Predecessor is 3; set 3.right = 4; go left
2
2
Predecessor is 1; set 1.right = 2; go left
3
1
No left child: output 1; follow right (the thread) to 2
4
2
Predecessor 1 already points to 2: remove the thread, output 2, go right
5
3
No left child: output 3; follow the thread to 4
6
4
Thread found: remove it, output 4, go right to 6
7
6, 5, 7
Same pattern: output 5, 6, 7
Complexity
Morris
Stack or recursion
Time
O(n): each edge is walked at most about three times
O(n)
Extra space
O(1)
O(h): O(log n) balanced, O(n) skewed
Modifies the tree
Temporarily (restored at the end)
No
The predecessor searches look expensive, but each one walks the right spine of a left subtree. Each such edge is walked once to create the thread and once to remove it, so the total work stays linear.
Advantages
Constant extra memory, which matters for very deep or very large trees and for memory-constrained environments.
No recursion-depth limits (Python’s limit is about 1,000 frames).
Can stop early (for example at the kth smallest element in a BST), though you must then remove any threads still in place.
Disadvantages
Issue
Why it matters
Modifies the tree during the traversal
Not safe while other threads read the tree, or on read-only or persistent structures
Higher constant factor
Extra pointer walks; often slower than a stack in practice
Early exit needs cleanup
Leaving threads in place corrupts the tree
Harder to read and maintain
More room for bugs
Variants
Morris preorder: output the node when the thread is created instead of when it is removed.
Morris postorder: possible, but it needs reversing right-spine segments; rarely worth it.
Related ideas: threaded binary trees keep such threads permanently, with a flag bit per pointer.
Edge Cases
Empty tree: returns [].
Right-skewed tree: no left children, so the traversal never creates a thread.
Left-skewed tree: every node gets a thread, still O(n).
Concurrent readers: unsafe; use a stack instead.
Interview Tips
Explain threads to the in-order predecessor and the “seen the thread twice” rule.
Justify the O(n) time by counting edge walks.
Mention the drawbacks: it temporarily modifies the tree and is not thread-safe. Interviewers often ask when you would not use it.
80
Discuss the Hardy-Ramanujan Theorem as it pertains to tree data structures.
KnownRevise
The Hardy–Ramanujan theorem (1917) is a result in number theory, not in tree data structures. It says that the number of distinct prime factors of n, written ω(n), is typically about ln ln n: for almost all integers, ω(n) stays within a small band around ln ln n. The theorem has no standard role in the design or analysis of tree data structures such as BSTs, heaps or B-trees, so be wary of sources that present one. The honest answer is to say what the theorem states, point to the loose connections people sometimes mean (factor trees, and other results by Hardy and Ramanujan used in counting), and name the results that actually are used to count trees.
Read full answerHide full answer
Applies tomathematics background for algorithm interviews (examples in Python 3.12)
What the Theorem Says
Statement
Meaning
Normal order of ω(n) is ln ln n
For almost all n, ω(n) = ln ln n + O((ln ln n)^(1/2 + ε))
Erdős–Kac theorem (1940) refines it
(ω(n) − ln ln n) / √(ln ln n) follows a standard normal distribution
Practical reading
Numbers have far fewer distinct prime factors than you might guess: n near 10^18 typically has about 4
A separate result by the same authors, the Hardy–Ramanujan asymptotic formula for integer partitions, p(n) ~ e^(π√(2n/3)) / (4n√3), is sometimes confused with it. “Hardy–Ramanujan number” usually refers to 1729, the smallest number expressible as a sum of two cubes in two ways.
Code Example
import math
from functools import lru_cache
def factor_tree(n: int) -> list[int]:
"""Prime factors found by repeatedly splitting n, as a factor tree does."""
factors, d = [], 2
while d * d <= n:
while n % d == 0:
factors.append(d)
n //= d
d += 1
if n > 1:
factors.append(n)
return factors
def omega(n: int) -> int:
"""Number of distinct prime factors, the quantity the theorem is about."""
return len(set(factor_tree(n)))
@lru_cache(maxsize=None)
def binary_tree_shapes(n: int) -> int:
"""Catalan number: distinct binary tree shapes with n nodes."""
return 1 if n <= 1 else sum(binary_tree_shapes(i) * binary_tree_shapes(n - 1 - i) for i in range(n))
print(factor_tree(360), omega(360)) # [2, 2, 2, 3, 3, 5] 3
N = 100_000
average = sum(omega(n) for n in range(2, N + 1)) / (N - 1)
print(round(average, 2), round(math.log(math.log(N)), 2)) # 2.66 2.44 (the mean is log log N + 0.26)
print([binary_tree_shapes(n) for n in range(1, 8)]) # [1, 2, 5, 14, 42, 132, 429]
print(5 ** (5 - 2)) # 125 labelled trees on 5 vertices (Cayley)
The average of ω(n) up to N is ln ln N + 0.2615 (Mertens’ constant), about 2.70 for N = 100,000, which is close to the measured 2.66. The theorem describes the typical value; the average includes rare numbers with many factors.
Where People Connect It to Trees
Connection
How strong
Factor trees (splitting n into factors until all leaves are prime)
The theorem says how many distinct prime leaves a typical factor tree has. This is a teaching diagram, not a data structure.
Hashing and sharding
Unrelated in practice; bucket counts are chosen as primes or powers of two for other reasons
Partition counting
Integer partitions correspond to some combinatorial structures, but tree-shape counting uses different tools
Results That Do Count Trees
Result
What it counts
Catalan numbers, C_n = (2n)! / ((n + 1)! n!)
Distinct binary tree shapes with n nodes: 1, 2, 5, 14, 42, …
Cayley’s formula, n^(n−2)
Labelled trees on n vertices (125 for n = 5)
Otter (1948)
Unlabelled trees grow like C · α^n · n^(−5/2), with α ≈ 2.9558
Random BST height
Expected height ≈ 4.311 ln n (Devroye, 1986)
Average BST search cost
About 2 ln n ≈ 1.39 log₂ n comparisons
These come from generating functions, singularity analysis and probabilistic arguments, not from the Hardy–Ramanujan theorem.
How to Answer in an Interview
State the theorem accurately: ω(n) is normally about ln ln n.
Say plainly that it is not a standard tool for tree data structures.
Offer the related results that are used, such as Catalan numbers for tree shapes and the expected height of random BSTs.
If the interviewer has a specific connection in mind, ask what it is rather than inventing one.
Common Pitfalls
Inventing a link to make the question fit: an interviewer who knows the subject will spot it.
Confusing the ω(n) theorem with the partition formula or the taxicab number 1729.
Saying “log” without the base: the theorem uses natural logarithms, although the base only shifts ln ln n by a constant.
Interview Tips
Being accurate about the limits of a connection reads as stronger than a confident but wrong answer.
Have Catalan numbers ready, since they answer “how many binary trees with n nodes?”.
81
How can Persistent Data Structures be implemented using Trees?
KnownRevise
A persistent data structure keeps every previous version available after an update. Each update returns a new version and leaves the old ones unchanged and still queryable. Trees make this efficient through path copying: an update copies only the nodes on the path from the root to the changed position, which is O(log n) nodes in a balanced tree, while all untouched subtrees are shared between the versions. Each version is just a pointer to its root. This technique is behind immutable maps in functional languages, Git’s object model, copy-on-write file systems and multi-version (MVCC) storage engines.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example: Persistent BST with Path Copying
from __future__ import annotations
from dataclasses import dataclass
@dataclass(frozen=True)
class PNode:
"""Immutable BST node: versions share every subtree they did not change."""
key: int
left: PNode | None = None
right: PNode | None = None
def insert(root: PNode | None, key: int) -> PNode:
"""Path copying: return a new root; only the O(h) nodes on the search path are copied."""
if root is None:
return PNode(key)
if key < root.key:
return PNode(root.key, insert(root.left, key), root.right)
if key > root.key:
return PNode(root.key, root.left, insert(root.right, key))
return root # already present: reuse this version
def keys(root: PNode | None) -> list[int]:
return [] if root is None else keys(root.left) + [root.key] + keys(root.right)
def count_nodes(root: PNode | None, seen: set[int]) -> None:
if root is not None and id(root) not in seen:
seen.add(id(root))
count_nodes(root.left, seen)
count_nodes(root.right, seen)
versions = [None]
for key in [50, 30, 70, 20, 40, 60, 80]:
versions.append(insert(versions[-1], key))
v8 = insert(versions[-1], 65)
print(keys(versions[7])) # [20, 30, 40, 50, 60, 70, 80]
print(keys(v8)) # [20, 30, 40, 50, 60, 65, 70, 80]
print(keys(versions[3])) # [30, 50, 70] (old versions still work)
print(v8.left is versions[7].left) # True: the whole left subtree is shared
shared = set()
for root in versions[1:] + [v8]:
count_nodes(root, shared)
print(len(shared)) # 21 distinct nodes for 8 versions (full copies would need 36)
Inserting 65 copies only the path 50 → 70 → 60, three nodes, plus the new node. The entire left subtree (30, 20, 40) is the same object in both versions.
Techniques
Technique
Idea
Cost per update
Path copying
Copy the root-to-leaf path; share the rest
O(log n) time and space (balanced)
Fat nodes
Each field stores a list of (version, value)
O(1) space; reads need a search by version
Node copying (Driscoll et al., 1989)
Spare modification slots per node; copy when full
O(1) amortized space, O(1) slowdown
Persistent balanced trees
Path copying on red-black, AVL or weight-balanced trees; rotations copy a few extra nodes
O(log n)
Hash array mapped tries (HAMT)
Wide (32-way) trie keyed by hash bits
O(log₃₂ n) nodes copied, effectively constant
Persistent segment trees
Path copying on a segment tree
O(log n) per point update
Levels of Persistence
Level
Can read
Can update
Partial
Any version
Only the newest
Full
Any version
Any version (versions form a tree)
Confluent
Any version
Can also merge two versions
Because insert accepts any old root, not only the newest, this BST is fully persistent.
Git: commits point to trees of objects; unchanged directories are shared between commits by hash.
Databases: copy-on-write B-trees (LMDB) and MVCC let readers see a snapshot while writers create new versions.
File systems: Btrfs and ZFS snapshots share unchanged blocks.
Algorithms: persistent segment trees answer “kth smallest in a range” and versioned range queries in O(log n).
Undo/redo and time travel debugging: keep a list of roots.
Complexity
Operation
Persistent balanced BST
Search any version
O(log n)
Insert/delete (new version)
O(log n) time, O(log n) new nodes
Space for m updates
O(n + m log n)
Snapshot
O(1): keep the root pointer
Edge Cases and Pitfalls
Unbalanced trees: sorted inserts make each path O(n) long, so each version copies O(n) nodes. Use a balanced tree.
Accidental mutation: a single in-place write corrupts every version that shares the node. Immutable node types (frozen=True here) prevent it.
Memory growth: old versions stay alive while referenced; garbage collection or reference counting reclaims unreachable nodes.
Recursion depth: recursive path copying is fine for balanced trees (height about 40 for a billion keys).
Interview Tips
Say “path copying: copy O(log n) nodes, share the rest”, then draw two roots sharing a subtree.
Name real systems: Git, Clojure maps, copy-on-write B-trees, MVCC.
Mention the difference between partial and full persistence.
82
Explain Heavy-Light Decomposition and its applications.
KnownRevise
Heavy-light decomposition (HLD) splits a rooted tree into vertex-disjoint chains, so that any path crosses only O(log n) chains. At each node, the child with the largest subtree is called heavy, and the edge to it is a heavy edge; every other child is light. Following heavy edges forms chains. Moving down a light edge at least halves the subtree size, so any root-to-node path uses at most log₂ n light edges. If each chain is laid out contiguously in an array, a segment tree or Fenwick tree over that array answers path queries and updates in O(log² n).
Read full answerHide full answer
Applies tocompetitive programming and tree algorithms (examples in Python 3.12)
Code Example: Path Sums with Point Updates
class HeavyLight:
"""Heavy-light decomposition with a Fenwick tree: path sums and point updates in O(log² n)."""
def __init__(self, n: int, edges: list[tuple[int, int]], values: list[int], root: int = 0) -> None:
adj = [[] for _ in range(n)]
for a, b in edges:
adj[a].append(b)
adj[b].append(a)
self.parent, self.depth = [-1] * n, [0] * n
size, heavy = [1] * n, [-1] * n
order, stack = [], [root]
while stack: # iterative DFS for parents and depths
u = stack.pop()
order.append(u)
for v in adj[u]:
if v != self.parent[u]:
self.parent[v], self.depth[v] = u, self.depth[u] + 1
stack.append(v)
for u in reversed(order): # subtree sizes, heaviest child
p = self.parent[u]
if p >= 0:
size[p] += size[u]
for u in order:
kids = [v for v in adj[u] if v != self.parent[u]]
if kids:
heavy[u] = max(kids, key=lambda v: size[v])
self.head, self.pos = [0] * n, [0] * n
current, stack = 0, [root]
while stack: # lay out each heavy chain contiguously
top = stack.pop()
u = top
while u != -1:
self.head[u], self.pos[u] = top, current
current += 1
for v in adj[u]:
if v != self.parent[u] and v != heavy[u]:
stack.append(v) # light child starts a new chain
u = heavy[u]
self.tree = [0] * (n + 1)
self.values = [0] * n
for u in range(n):
self.update(u, values[u])
def _add(self, i: int, delta: int) -> None:
i += 1
while i < len(self.tree):
self.tree[i] += delta
i += i & -i
def _prefix(self, i: int) -> int:
total = 0
while i > 0:
total += self.tree[i]
i -= i & -i
return total
def update(self, u: int, value: int) -> None:
self._add(self.pos[u], value - self.values[u])
self.values[u] = value
def path_sum(self, a: int, b: int) -> int:
"""Sum of values on the path a..b: at most O(log n) chains, each one range query."""
total = 0
while self.head[a] != self.head[b]:
if self.depth[self.head[a]] < self.depth[self.head[b]]:
a, b = b, a
h = self.head[a]
total += self._prefix(self.pos[a] + 1) - self._prefix(self.pos[h])
a = self.parent[h] # jump over the whole chain
lo, hi = sorted((self.pos[a], self.pos[b]))
return total + self._prefix(hi + 1) - self._prefix(lo)
# 0
# / \
# 1 2
# / \ \
# 3 4 5
# /
# 6
edges = [(0, 1), (0, 2), (1, 3), (1, 4), (2, 5), (3, 6)]
hld = HeavyLight(7, edges, values=[5, 3, 8, 2, 7, 1, 4])
print(hld.path_sum(6, 5)) # 23 (4 + 2 + 3 + 5 + 8 + 1)
print(hld.path_sum(4, 6)) # 16 (7 + 3 + 2 + 4)
hld.update(1, 10)
print(hld.path_sum(6, 5)) # 30
print(hld.head) # [0, 0, 2, 0, 4, 2, 0]
path_sum(6, 5): 6 is on chain 0 and 5 is on chain 2. Chain 2’s head is deeper, so the code adds that chain’s segment (8 + 1) and jumps to the head’s parent, node 0. Now both ends are on chain 0, and one range query adds 5 + 3 + 2 + 4. Total: 23.
Why O(log n) Chains
When you go from node u to a light child v, size(v) ≤ size(u) / 2, because otherwise v would be the heavy child. Sizes can halve at most log₂ n times, so a path from the root meets at most log₂ n light edges, and therefore at most log₂ n + 1 chains. A path between a and b goes up from both ends, so it meets O(log n) chains.
Complexity
Operation
Time
Decomposition (sizes, heavy children, positions)
O(n)
Path query or path update
O(log n) chains × O(log n) per range query = O(log² n)
LCA as a by-product
O(log n)
Space
O(n)
Assigning positions in a DFS that visits the heavy child first also makes every subtree one contiguous range, so subtree queries cost O(log n).
Applications
Problem
How HLD helps
Path sum, max or min with updates
Range queries over the chains on the path
Maximum edge weight on a path (network bottleneck)
Store each edge’s weight at its child node
Path assignment (“set all values on a path”)
Segment tree with lazy propagation
LCA
Climb chains until both nodes are on one chain
Edge Cases and Pitfalls
Recursion depth: sizes and chains computed recursively overflow on deep trees; this code is iterative.
Edge values versus node values: store each edge’s value on its deeper endpoint, and exclude the LCA when summing a path.
Interview Tips
Explain heavy = largest subtree, then prove that a light edge halves the size.
Present the result as O(log n) chains × O(log n) range query = O(log² n).
Mention binary lifting for static values and link-cut trees when the tree’s shape changes.
83
Describe a Universal Value Tree and its uniqueness in tree structures.
KnownRevise
A universal value (unival) tree is a tree in which every node holds the same value. The idea is used most often in the problem “count the unival subtrees”, where a subtree means a node together with all its descendants. A subtree is unival when both child subtrees are unival and each existing child has the same value as the node. A post-order pass answers this for every node at once, in O(n). What makes it distinctive is that unival status is a bottom-up property: every leaf is trivially unival, and a parent’s status depends only on its children’s results and values.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def is_unival(root: Node | None) -> bool:
"""True if every node in the tree holds the same value."""
if root is None:
return True
stack = [root]
while stack:
node = stack.pop()
if node.val != root.val:
return False
stack.extend(c for c in (node.left, node.right) if c)
return True
def count_unival_subtrees(root: Node | None) -> int:
"""Count subtrees (a node and all its descendants) whose values are all equal: O(n)."""
count = 0
def check(node: Node | None) -> bool:
nonlocal count
if node is None:
return True
left_ok, right_ok = check(node.left), check(node.right) # visit both sides always
if not (left_ok and right_ok):
return False
if node.left and node.left.val != node.val:
return False
if node.right and node.right.val != node.val:
return False
count += 1
return True
check(root)
return count
tree = build([5, 1, 5, 5, 5, None, 5])
print(is_unival(tree), count_unival_subtrees(tree)) # False 4
print(is_unival(build([2, 2, 2])), count_unival_subtrees(build([2, 2, 2]))) # True 3
print(count_unival_subtrees(None)) # 0
Walkthrough: [5, 1, 5, 5, 5, None, 5]
5
/ \
1 5
/ \ \
5 5 5
Subtree root
Children unival?
Children equal to node?
Unival?
Count
left-left 5 (leaf)
yes
no children
yes
1
left-right 5 (leaf)
yes
no children
yes
2
1
yes
no (5 ≠ 1)
no
2
right-right 5 (leaf)
yes
no children
yes
3
right 5
yes
yes
yes
4
root 5
no (the left side failed)
no
4
Properties
Property
Detail
Every leaf is a unival subtree
So the count is at least the number of leaves
A subtree of a unival subtree is unival
Unival status propagates downward
If the whole tree is unival
The count equals n
Status depends only on children
So one post-order pass is enough
Complexity
Approach
Time
Space
Post-order returning a boolean (above)
O(n)
O(h) call stack
Check every subtree separately with is_unival
O(n²) worst case
O(h)
Why Visit Both Children Every Time
The code computes check(node.left) and check(node.right)before combining them. If it used check(left) and check(right), short-circuiting would skip the right subtree whenever the left failed, and its unival subtrees would never be counted.
Variations
Variant
Change
N-ary tree
All children must be unival and equal to the node
Longest univalue path
Count edges between equal-valued neighbours, like the diameter problem
Largest unival subtree
Return sizes instead of booleans
Is the whole tree unival?
Compare every node with the root (the first function)
Uses
An interview exercise for the “return information upward” pattern (post-order).
Compressing quad-trees and similar spatial trees: a region whose children all hold the same value (for example, a uniform colour in an image quadtree) is collapsed into one leaf.
Detecting uniform regions in configuration trees or UI component trees.
Edge Cases
Empty tree: 0 unival subtrees (by convention; some versions say the empty tree is unival but count 0).
Single node: 1.
Deep trees: the recursion depth equals the height; convert it to an iterative post-order for very deep inputs.
Common Pitfalls
Short-circuit evaluation skipping the right subtree.
Reading a missing child’s value (node.left.val when node.left is None) instead of checking that the child exists first.
Counting a parent as unival when its children are unival but hold a different value.
Interview Tips
Define a subtree precisely (a node and all its descendants).
Explain the post-order pattern and the short-circuit trap.
Mention the quadtree compression use for a practical example.
84
What is a tree invariant, and how do AVL trees maintain it?
KnownRevise
A tree invariant is a property that must be true before and after every operation on the tree. Code may break it temporarily in the middle of an update, but it must restore it before the operation returns. Every BST maintains the ordering invariant: left subtree keys < node key < right subtree keys. AVL trees add the balance invariant: at every node, the heights of the two subtrees differ by at most 1. Together, these guarantee a height of about 1.44 log₂ n, and so O(log n) search, insert and delete. AVL trees maintain the balance invariant by updating stored heights on the way back up from an insert or delete and applying rotations wherever the difference reaches 2.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Invariants of an AVL Tree
Invariant
Statement
Why it matters
Ordering
In-order keys are strictly increasing
Searching by comparisons works
Balance
‘
height(left) − height(right)
≤ 1` at every node
Height stays O(log n)
Stored-height accuracy
node.height = 1 + max(child heights)
Balance checks are O(1) per node
Code Example
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class AVLNode:
key: int
left: AVLNode | None = None
right: AVLNode | None = None
height: int = 1 # nodes on the longest downward path
def h(node: AVLNode | None) -> int:
return node.height if node else 0
def fix_height(node: AVLNode) -> None:
node.height = 1 + max(h(node.left), h(node.right))
def rotate_right(y: AVLNode) -> AVLNode:
x = y.left
y.left, x.right = x.right, y # BST order kept: x.right moves under y
fix_height(y)
fix_height(x)
return x
def rotate_left(x: AVLNode) -> AVLNode:
y = x.right
x.right, y.left = y.left, x
fix_height(x)
fix_height(y)
return y
def rebalance(node: AVLNode) -> AVLNode:
"""Restore |balance| <= 1 at this node with one single or double rotation."""
fix_height(node)
balance = h(node.left) - h(node.right)
if balance > 1:
if h(node.left.left) < h(node.left.right):
node.left = rotate_left(node.left) # left-right case
return rotate_right(node)
if balance < -1:
if h(node.right.right) < h(node.right.left):
node.right = rotate_right(node.right) # right-left case
return rotate_left(node)
return node
def insert(node: AVLNode | None, key: int) -> AVLNode:
if node is None:
return AVLNode(key)
if key < node.key:
node.left = insert(node.left, key)
elif key > node.key:
node.right = insert(node.right, key)
else:
return node
return rebalance(node) # every ancestor on the path is checked
def check_invariants(node: AVLNode | None, low=float("-inf"), high=float("inf")) -> int:
"""Raise if BST order, stored heights or the balance rule are broken; return the height."""
if node is None:
return 0
assert low < node.key < high, "BST order broken"
left = check_invariants(node.left, low, node.key)
right = check_invariants(node.right, node.key, high)
assert node.height == 1 + max(left, right), "stored height is stale"
assert abs(left - right) <= 1, "balance invariant broken"
return node.height
root = None
for key in range(1, 1024): # sorted input: the worst case for a plain BST
root = insert(root, key)
print(check_invariants(root)) # 10 (a plain BST would have height 1023)
broken = AVLNode(2, AVLNode(1, AVLNode(0, height=1), height=2), height=3)
try:
check_invariants(broken)
except AssertionError as error:
print(error) # balance invariant broken
check_invariants is an O(n) validator to call in tests after every operation.
How Insertion Restores Balance
Insert as in a BST. Only the nodes on the path from the root to the new leaf can change height.
On the way back up, update each node’s height and compute balance = height(left) − height(right).
If balance is +2 or −2, rotate:
Case
Condition
Fix
Left-left
balance = +2, left child leans left or is level
Single right rotation
Left-right
balance = +2, left child leans right
Rotate the left child left, then rotate right
Right-right
balance = −2, right child leans right or is level
Single left rotation
Right-left
balance = −2, right child leans left
Rotate the right child right, then rotate left
A rotation keeps the ordering invariant, because it only moves one subtree between two nodes whose key ranges are compatible. It also lowers the subtree’s height back to its value before the insert. Each rotation updates the lower node’s height before the new root’s, or later balance checks read stale heights. For insertion, one rebalancing (single or double rotation) is enough. Deletion may need rotations at several levels, up to O(log n).
Why the Balance Invariant Bounds the Height
Let N(h) be the minimum number of nodes in an AVL tree of height h. Then N(h) = N(h − 1) + N(h − 2) + 1, which grows like the Fibonacci numbers, about φ^h with φ ≈ 1.618. So n ≥ φ^h roughly, and h ≤ about 1.44 log₂ n. The example inserts 1,023 sorted keys and gets height 10 in this code’s node-counting convention, while a plain BST would be a chain of height 1,023.
Invariants in Other Self-Balancing Trees
Tree
Invariant
Maintained by
Red-black
No red node has a red child; every root-to-leaf path has the same number of black nodes
Recolouring + at most 2 rotations per insert, 3 per delete
B-tree
Every node except the root is at least half full; all leaves at the same depth
Splits and merges
Treap
BST order on keys, heap order on random priorities
Rotations
Splay tree
Only BST order (no balance invariant)
Amortized O(log n) through splaying
Binary heap
Each parent ≤ its children; shape is a complete tree
Sift up and sift down
Interview Tips
Define invariant first: a property that holds between operations.
Name the AVL invariants (ordering, balance, accurate heights) and the four rotation cases.
Mention writing an invariant checker for tests, as shown above.
85
How do File Systems use trees to manage files and directories?
KnownRevise
File systems use trees at two levels. The one users see is the directory hierarchy: a rooted tree of directories and files, in which every path such as /home/ada/notes.txt is a route from the root. Underneath, file systems use search trees (mostly B-trees and B+ trees) to index their metadata: large directories by file name, each file’s data blocks (extent trees), free space, and in modern copy-on-write file systems almost everything. Trees give logarithmic lookups, cheap inserts and deletes, and ordered traversal while staying shallow on disk.
Read full answerHide full answer
Applies toLinux (ext4, XFS, Btrfs), Windows (NTFS), macOS (APFS) and ZFS, conceptually
A directory is a special file whose content maps names to inode numbers (Unix) or to file records (NTFS’s Master File Table).
An inode stores metadata (size, owner, permissions, timestamps) and where the data lives, but not the name. The name exists only in the parent directory’s entry.
Path resolution walks the tree one component at a time: look up home in /, then ada in that directory, then notes.txt. Linux caches the results in the dentry cache, so repeated lookups avoid disk reads.
Hard links let several names point to one inode, so files form a DAG rather than a strict tree. Hard links to directories are not allowed (apart from . and ..), which keeps the directory structure a tree and avoids cycles. Symbolic links are separate files that store a path.
Level 2: Trees Inside the File System
Structure
Tree used
Example systems
Large directories (name → inode)
Hashed B-tree-like index (HTree) or B+ tree
ext4 HTree; XFS, NTFS, APFS and Btrfs B-trees
File data location (offset → disk blocks)
Extent tree: each entry maps a run of contiguous blocks
ext4 extents, XFS B+ tree of extents
Free space
B+ trees indexed by block number and by extent size
XFS
All metadata, copy-on-write
Copy-on-write B-trees: modified nodes are written to new locations
Btrfs, APFS
Block pointers with checksums
Merkle-style tree: each parent stores its children’s checksums
ZFS
Why Trees Fit
Requirement
How a tree meets it
A folder with a million files
A B-tree on names finds one in a few node reads; a linear list would scan all entries
Fast random access in a 100 GB file
An extent tree maps a byte offset to its block in O(log n)
Sorted listings and prefix scans
B-trees keep names ordered
Crash safety and snapshots
Copy-on-write trees never overwrite live nodes. A new root is written last, so a crash leaves either the old tree or the new one, and a snapshot is a saved root pointer
Integrity
Checksums in parent nodes (ZFS, Btrfs) detect corruption anywhere below
Common Operations and Their Cost
Operation
Work
Open /a/b/c
One directory lookup per component, each O(log entries) with indexed directories
Rename within a file system
Change two directory entries; the data does not move
ls on a large directory
Ordered walk of the directory’s B-tree leaves
du or find
Depth-first traversal of the directory tree
Snapshot (Btrfs, ZFS, APFS)
O(1): keep the old root; changed blocks are copied later
Edge Cases and Pitfalls
Deep paths: Linux limits a path to PATH_MAX = 4,096 bytes. Recursive tools may hit recursion limits on very deep trees, so robust tools use iterative walks.
Symlink loops: traversal tools must detect cycles, for example by tracking device and inode pairs, as find -L does.
Hard-linked files: counting disk usage per path double-counts them unless inodes are tracked.
Many tiny files: each uses an inode and directory entry, so metadata trees can dominate performance.
Interview Tips
Separate the logical tree (directories) from the index trees (B-trees and extent trees) inside the file system.
Explain inodes versus names, and why directory hard links are forbidden.
Mention copy-on-write B-trees for snapshots and crash consistency.
86
Discuss how trees enable Efficient Undo/Redo Operations in text editors or IDEs.
KnownRevise
A simple editor keeps two stacks: undo pops the last change and pushes it onto the redo stack. The weakness is that any new edit after an undo clears the redo stack, so that branch of history is lost for good. An undo tree stores every state as a node whose parent is the state it came from. Undo moves to the parent, and redo moves to a child. A new edit after an undo creates a new branch, so nothing is lost. Editors also rely on trees for the text itself: piece tables and ropes stored in balanced trees make each edit and its inverse cheap, so undo and redo stay fast in large files.
Read full answerHide full answer
Applies toeditor and IDE design (examples in Python 3.12)
Code Example: An Undo Tree
from __future__ import annotations
from dataclasses import dataclass, field
@dataclass
class State:
text: str
parent: State | None = None
children: list[State] = field(default_factory=list)
class UndoTree:
"""Undo history as a tree: editing after an undo starts a new branch instead of deleting redo."""
def __init__(self, text: str = "") -> None:
self.root = self.current = State(text)
def edit(self, new_text: str) -> None:
child = State(new_text, parent=self.current)
self.current.children.append(child)
self.current = child
def undo(self) -> str:
if self.current.parent:
self.current = self.current.parent
return self.current.text
def redo(self, branch: int = -1) -> str:
"""Follow the newest branch by default, or any older branch by index."""
if self.current.children:
self.current = self.current.children[branch]
return self.current.text
history = UndoTree("")
history.edit("Hello")
history.edit("Hello, world")
print(history.undo()) # Hello
history.edit("Hello, Ada") # a linear stack would lose "Hello, world" here
print(history.undo()) # Hello
print(history.redo(0)) # Hello, world (the older branch is still reachable)
print(history.undo(), "|", history.redo()) # Hello | Hello, Ada
print(len(history.root.children[0].children)) # 2 branches after "Hello"
Real editors store changes (insert “world” at offset 7) rather than full copies of the text. Applying a change moves forward, and applying its inverse moves back.
Linear Stacks Versus an Undo Tree
Aspect
Undo and redo stacks
Undo tree
Undo, redo
O(1)
O(1) to move between parent and child
New edit after undo
Redo history is discarded
A new branch is added
Recover an abandoned edit
Impossible
Walk to that branch
Memory
Only the current line of history
Every branch; editors prune old ones
User interface
Simple
Needs a way to pick branches, or navigation by time
Vim keeps an undo tree natively: u and Ctrl-R move along the current branch, while g- and g+ move through states in chronological order across branches, and :undolist shows the leaves. Emacs offers it through the undo-tree or vundo packages. Most IDEs, including VS Code, keep linear undo, but with local history of saved files as a fallback.
Trees That Make Each Undo Step Cheap
Structure
Use
Why it helps undo
Piece table stored in a balanced tree (VS Code’s text buffer is a red-black “piece tree”)
Represents the document as references into the original and an append-only buffer
An edit adds or splits a few pieces in O(log n); undo restores them without copying text
Rope (balanced binary tree of string chunks)
Large documents
Insert and delete in O(log n); with persistent nodes, an old version is just an old root
Persistent trees
Versioned documents
Each version shares unchanged subtrees, so many snapshots cost little memory
Syntax trees (incremental parsers such as tree-sitter)
Highlighting and code navigation
After undo, only the changed region is reparsed
Grouping and Merging Changes
Typing “hello” should undo as one step, so editors group changes by time, word boundaries or a pause in typing.
Refactorings such as a rename across files are recorded as one compound command (the Command pattern), so a single undo reverts them.
Collaborative editors cannot simply pop a global stack, because other users’ edits are interleaved. They use operational transformation or CRDTs to undo only the local user’s changes, adjusted for later remote edits.
Complexity
Operation
Undo tree with change records
Undo, redo
O(cost of applying one change), O(log n) with a piece tree or rope
Jump to an old state
O(path length) changes applied
Memory
O(total changes); prune or compress old branches
Edge Cases and Pitfalls
Unbounded growth: cap the number of states or merge old ones.
Saving and reloading: persist the undo history (Vim’s undofile) or the tree is lost on close.
External file changes: reloading from disk usually becomes a new state rather than clearing history.
Large pastes: store a reference to the pasted text, not repeated copies.
Interview Tips
Start with two stacks, show how redo is lost, then introduce the undo tree.
Mention storing changes, not snapshots, and the Command pattern.
Bring in piece tables or ropes for cheap edits, and CRDTs or OT for collaborative undo.
87
Explain the use of Tree Structures in managing hierarchical data in relational databases.
KnownRevise
Relational tables are flat, but a lot of data is hierarchical: product categories, organisation charts, comment threads, folders and bills of materials. There are four standard ways to store a tree in SQL: the adjacency list (a parent_id column, queried with recursive CTEs), the closure table (one row per ancestor–descendant pair), nested sets (left and right numbers from a depth-first walk) and the materialized path (a string such as 1/2/3, or PostgreSQL’s ltree type). They trade write cost against read cost. The adjacency list is the default and is simple to update, and the others make subtree reads faster.
Read full answerHide full answer
Applies toSQL databases (PostgreSQL, MySQL 8+, SQL Server, SQLite 3.8.3+); example run on SQLite through Python 3.12
Code Example
import sqlite3
db = sqlite3.connect(":memory:")
db.executescript("""
CREATE TABLE category (
id INTEGER PRIMARY KEY,
parent_id INTEGER REFERENCES category(id), -- adjacency list: one parent pointer per row
name TEXT NOT NULL
);
INSERT INTO category VALUES
(1, NULL, 'Electronics'), (2, 1, 'Computers'), (3, 2, 'Laptops'),
(4, 2, 'Desktops'), (5, 1, 'Phones'), (6, 3, 'Gaming laptops');
-- Closure table: one row per (ancestor, descendant) pair, including each node with itself.
CREATE TABLE category_closure (ancestor INTEGER, descendant INTEGER, depth INTEGER,
PRIMARY KEY (ancestor, descendant));
""")
# Whole subtree under Computers with a recursive CTE (works in PostgreSQL, MySQL 8+, SQLite).
subtree = db.execute("""
WITH RECURSIVE sub(id, name, depth) AS (
SELECT id, name, 0 FROM category WHERE id = 2
UNION ALL
SELECT c.id, c.name, sub.depth + 1 FROM category c JOIN sub ON c.parent_id = sub.id
)
SELECT name, depth FROM sub ORDER BY depth, name
""").fetchall()
print(subtree) # [('Computers', 0), ('Desktops', 1), ('Laptops', 1), ('Gaming laptops', 2)]
# Breadcrumb path from a leaf up to the root.
path = db.execute("""
WITH RECURSIVE up(id, parent_id, name, depth) AS (
SELECT id, parent_id, name, 0 FROM category WHERE id = 6
UNION ALL
SELECT c.id, c.parent_id, c.name, up.depth + 1 FROM category c JOIN up ON c.id = up.parent_id
)
SELECT group_concat(name, ' > ') FROM (SELECT name FROM up ORDER BY depth DESC)
-- SQLite keeps the subquery order; PostgreSQL: string_agg(name, ' > ' ORDER BY depth DESC)
""").fetchone()[0]
print(path) # Electronics > Computers > Laptops > Gaming laptops
# Fill the closure table once; afterwards subtree queries need no recursion.
db.execute("""
INSERT INTO category_closure
WITH RECURSIVE pairs(ancestor, descendant, depth) AS (
SELECT id, id, 0 FROM category
UNION ALL
SELECT p.ancestor, c.id, p.depth + 1 FROM pairs p JOIN category c ON c.parent_id = p.descendant
)
SELECT * FROM pairs
""")
count = db.execute("SELECT COUNT(*) FROM category_closure WHERE ancestor = 1 AND depth > 0").fetchone()[0]
print(count) # 5 descendants of Electronics
The Four Models
Model
Stores
Subtree read
Move a subtree
Notes
Adjacency list
parent_id per row
Recursive CTE, one join per level
Update one row
Simple, normalized, foreign key keeps integrity
Closure table
Every (ancestor, descendant, depth) pair
Single indexed join
Delete and reinsert many pairs
O(n · depth) rows; fast ancestor and descendant queries
Nested sets
lft, rgt numbers from a DFS
WHERE lft BETWEEN parent.lft AND parent.rgt
Renumber up to O(n) rows
Very fast reads; expensive inserts; good for rarely changing trees
Materialized path
'1/2/3/' or ltree'electronics.computers.laptops'
Prefix match (LIKE '1/2/%' with an index, or ltree <@)
Rewrite the paths of the whole subtree
Easy breadcrumbs; path length limits depth
SQL Server also has a built-in hierarchyid type, a compact materialized path with tree methods.
Many “all descendants or all ancestors” queries, moderate size
Closure table
Mostly static trees with heavy reads (category menus)
Nested sets or materialized path
PostgreSQL with label-based paths
ltree with a GiST index
Combined
Adjacency list as the source of truth plus a closure table maintained by triggers or application code
Query Patterns
Question
Adjacency list
Closure table
Children of X
WHERE parent_id = X
WHERE ancestor = X AND depth = 1
All descendants
Recursive CTE downward
WHERE ancestor = X AND depth > 0
Path to the root (breadcrumbs)
Recursive CTE upward
WHERE descendant = X ORDER BY depth DESC
Depth of a node
CTE counter
MAX(depth) where descendant = X
Is A an ancestor of B?
CTE
Single row lookup
Indexes and Integrity
Index parent_id for adjacency lists, and (ancestor, depth) plus (descendant) for closure tables.
A foreign key on parent_id prevents orphans; use ON DELETE CASCADE or RESTRICT deliberately.
Cycles (A is the parent of B and B the parent of A) are not prevented by foreign keys. Check in application code or a trigger, and guard recursive CTEs with a depth limit, or with the CYCLE clause in PostgreSQL 14+.
Edge Cases and Pitfalls
Unbounded recursion: bad data with a cycle makes a recursive CTE run until it hits a limit; add WHERE depth < 100.
Ordering siblings: add a position column, since rows have no natural order.
Large moves: in nested sets and materialized paths, moving a big subtree rewrites many rows; schedule it or choose another model.
ORMs: many need plugins for recursive queries (for example django-mptt or django-treebeard, or Rails’ ancestry or closure_tree gems).
Interview Tips
Name the four models and their read versus write trade-offs.
Write a recursive CTE for descendants from memory.
Recommend adjacency list + recursive CTE as the default, and a closure table when subtree queries dominate.
88
Describe a system design that efficiently indexes data using tree structures.
KnownRevise
A strong answer designs an indexing service around the query patterns, then chooses a tree for each pattern. B+ trees serve point lookups and range scans on keys, and LSM trees (sorted in-memory trees flushed to sorted files) absorb heavy writes. Tries or finite-state transducers support prefix and autocomplete queries, R-trees handle geospatial queries, and Merkle trees detect differences between replicas cheaply. The example below indexes orders for an e-commerce platform: lookups by ID, time ranges per customer, product-name autocomplete and “stores near me”.
Read full answerHide full answer
Applies tosystem design interviews; storage engines such as PostgreSQL, MySQL/InnoDB, RocksDB, Cassandra, Elasticsearch/Lucene and PostGIS
Requirements
Query
Example
Needs
Point lookup
Order #981234
O(log n) by key
Range
Orders for customer 42 in October
Sorted keys, range scan
Prefix
Products starting with “lapt”
Prefix index
Geospatial
Stores within 5 km
2-D index
Replication check
Are replicas A and B identical?
Compare without sending all data
Scale assumption: about 1 billion orders, 20,000 writes per second at peak and 100,000 reads per second.
Architecture
Clients -> API service -> Index router (shards by hash of customer_id)
|
+-------------+-------------+
Shard 1 Shard 2 ... Shard N each shard: 3 replicas
- LSM tree: (customer_id, created_at, order_id) -> order summary
- B+ tree (in the relational store): order_id -> full order
Search cluster: FST/trie term dictionary for product names
Geo index: R-tree (PostGIS GiST) on store locations
Anti-entropy: Merkle tree per key range between replicas
Choosing the Tree for Each Job
Tree
Used for
Why
B+ tree
Primary key and secondary indexes in the relational store
3–4 levels for billions of rows, ordered leaves for ranges, mature concurrency control
LSM tree (memtable as a skip list or balanced tree, plus sorted SSTables)
Compare root hashes; descend only into ranges that differ
Write Path
The API writes the order to the relational primary, where B+ tree indexes are updated in the same transaction.
A change-data-capture stream publishes the event.
Consumers update the LSM-based per-customer index and the search index asynchronously, so those indexes are eventually consistent, typically within seconds.
Read Path
GET /orders/981234 → primary-key B+ tree lookup, served from cache when hot.
GET /customers/42/orders?from=2026-10-01 → one shard, one range scan on (customer_id, created_at).
Autocomplete → search cluster, prefix walk plus popularity ranking.
Nearby stores → R-tree query with a distance filter.
Trade-offs
Decision
Benefit
Cost
Shard by customer_id
Customer queries hit one shard
Global time-range queries scatter to every shard
LSM for event indexes
High write throughput
Read amplification; compaction uses I/O
Secondary indexes updated asynchronously
Fast writes
Briefly stale results
Many indexes
Fast varied queries
Every index adds write cost and storage
Scaling and Operations
Hot keys (one huge customer): split by (customer_id, month).
Index bloat: monitor size and rebuild or vacuum B+ tree indexes; tune LSM compaction.
Caching: the top B+ tree levels stay in memory; cache popular lookups.
Backfills: build new indexes online, then switch reads over.
Interview Tips
Start from the queries, then pick a tree per access pattern.
Explain B+ tree versus LSM tree in terms of reads versus writes.
Mention Merkle trees for replica consistency and R-trees for geodata to show breadth.
89
How are Decision Trees used in Machine Learning for classification and regression?
KnownRevise
A decision tree predicts by asking a sequence of yes/no questions about the features (for example, “is monthly spend ≤ 50?”), starting at the root and following the answers down to a leaf. For classification, the leaf returns the majority class (or class probabilities); for regression, it returns the mean target value of its training samples. Training is greedy and recursive: at each node, pick the feature and threshold that best separates the targets, using Gini impurity or entropy for classes and variance (squared error) for numbers, then split and repeat until a stopping rule applies. Trees are interpretable, need no feature scaling and model non-linear interactions, but a single tree overfits easily, which is why random forests and gradient-boosted trees are used in practice.
Read full answerHide full answer
Applies tomachine learning (CART algorithm; example implemented from scratch in Python 3.12)
Code Example: A Small CART Classifier
from collections import Counter
def gini(labels: list[str]) -> float:
"""Gini impurity: chance two random picks from the node have different labels."""
n = len(labels)
return 1 - sum((c / n) ** 2 for c in Counter(labels).values())
def best_split(rows: list[list[float]], labels: list[str]):
"""Try every feature and threshold; keep the split with the lowest weighted impurity."""
best = None
for feature in range(len(rows[0])):
for threshold in sorted({row[feature] for row in rows}):
left = [y for row, y in zip(rows, labels) if row[feature] <= threshold]
right = [y for row, y in zip(rows, labels) if row[feature] > threshold]
if not left or not right:
continue
score = (len(left) * gini(left) + len(right) * gini(right)) / len(labels)
if best is None or score < best[0]:
best = (score, feature, threshold)
return best
def grow(rows, labels, depth=0, max_depth=3, min_samples=2):
"""CART-style classification tree as nested dicts; leaves hold the majority label."""
if depth == max_depth or len(labels) < min_samples or len(set(labels)) == 1:
return Counter(labels).most_common(1)[0][0]
split = best_split(rows, labels)
if split is None:
return Counter(labels).most_common(1)[0][0]
_, feature, threshold = split
go_left = [row[feature] <= threshold for row in rows]
pick = lambda side: ([r for r, g in zip(rows, go_left) if g == side],
[y for y, g in zip(labels, go_left) if g == side])
return {"feature": feature, "threshold": threshold,
"left": grow(*pick(True), depth + 1, max_depth, min_samples),
"right": grow(*pick(False), depth + 1, max_depth, min_samples)}
def predict(tree, row):
while isinstance(tree, dict):
tree = tree["left"] if row[tree["feature"]] <= tree["threshold"] else tree["right"]
return tree
# features: [monthly_spend, support_tickets]; label: did the customer churn?
rows = [[20, 5], [25, 4], [80, 0], [90, 1], [30, 6], [85, 3], [22, 0], [75, 5]]
labels = ["yes", "yes", "no", "no", "yes", "no", "no", "yes"]
model = grow(rows, labels)
print(round(gini(labels), 3)) # 0.5
print(model) # {'feature': 1, 'threshold': 3, 'left': 'no', 'right': 'yes'}
print(predict(model, [24, 5]), predict(model, [88, 0])) # yes no
The root has Gini impurity 0.5 (four churners, four non-churners). Splitting on support tickets ≤ 3 gives two pure leaves, so the weighted impurity drops to 0, and growth stops.
Split Criteria
Task
Criterion
Formula (per node)
Classification
Gini impurity (CART default)
1 − Σ pₖ²
Classification
Entropy / information gain (ID3, C4.5)
−Σ pₖ log₂ pₖ
Regression
Squared error (variance reduction)
mean of (y − ȳ)²
Regression
Absolute error
mean absolute distance from the median
The best split maximises the drop in impurity, weighted by how many samples go to each side.
Controlling Overfitting
Technique
Effect
max_depth
Limits the number of questions on any path
min_samples_split, min_samples_leaf
Prevents tiny, noisy leaves
max_features
Considers a random subset of features at each split (used by forests)
Cost-complexity pruning (ccp_alpha in scikit-learn)
Grows a full tree, then removes branches that add little
Cross-validation
Chooses these settings on held-out data
In scikit-learn, the corresponding classes are DecisionTreeClassifier(criterion="gini") and DecisionTreeRegressor(criterion="squared_error").
Single Trees Versus Ensembles
Model
How it uses trees
Strength
Decision tree
One tree
Interpretable rules
Random forest
Many deep trees on bootstrap samples with random feature subsets; average or vote
Robust and low-variance; little tuning needed
Gradient boosting (XGBoost, LightGBM, CatBoost)
Shallow trees added one at a time, each fitting the previous model’s errors
Often the strongest choice for tabular data
Strengths and Weaknesses
Strengths
Weaknesses
Easy to explain and visualise
High variance: small data changes can produce a different tree
Handles numeric and categorical features (with suitable encoding)
Regression output is piecewise constant and cannot extrapolate
Fast prediction: O(depth)
Biased toward features with many distinct values (for impurity-based importance)
Complexity
Phase
Cost
Training (sorting each feature once per level)
About O(n · d · log n) for a balanced tree with n samples and d features
Prediction
O(depth) per sample
This teaching implementation
O(d · n²) per node, since it re-scans the rows for each threshold
Edge Cases and Pitfalls
Class imbalance: use class weights or balanced sampling, or the tree predicts the majority class everywhere.
Data leakage: features derived from the target produce misleadingly perfect splits.
Feature importance: impurity-based importance can mislead; check permutation importance.
Missing values: handle them explicitly (imputation, or a library that supports them).
Interview Tips
Explain greedy splitting with Gini or entropy, and variance for regression.
Discuss overfitting and the controls for it.
Know why random forests reduce variance and boosting reduces bias.
90
Discuss the role of Segment Trees in computational geometry and data analysis.
KnownRevise
A segment tree is a balanced binary tree over a range of positions or coordinates. Each node stores a summary of its range, so it answers range queries and updates in O(log n). In computational geometry, it is the standard tool for sweep-line algorithms. As a vertical line sweeps across the plane, the tree keeps track of which y-intervals are currently covered, which solves problems such as the area or perimeter of a union of rectangles and counting segment intersections in O(n log n). The classic geometric variant stores intervals in O(log n) canonical nodes to answer stabbing queries (“which intervals contain this point?”). In data analysis, segment trees give fast range aggregates (sum, min, max) over time series and arrays that keep changing.
Read full answerHide full answer
Applies toalgorithms and data processing (examples in Python 3.12)
Code Example: Area of a Union of Rectangles
def union_area(rects: list[tuple[int, int, int, int]]) -> int:
"""Area covered by axis-aligned rectangles (x1, y1, x2, y2): sweep line + segment tree."""
ys = sorted({y for _, y1, _, y2 in rects for y in (y1, y2)}) # coordinate compression
index = {y: i for i, y in enumerate(ys)}
segments = len(ys) - 1
cover = [0] * (4 * max(segments, 1)) # how many rectangles fully cover this node's range
covered = [0] * (4 * max(segments, 1)) # total covered length inside this node's range
def update(node: int, lo: int, hi: int, a: int, b: int, delta: int) -> None:
if b <= lo or hi <= a:
return
if a <= lo and hi <= b:
cover[node] += delta
else:
mid = (lo + hi) // 2
update(2 * node, lo, mid, a, b, delta)
update(2 * node + 1, mid, hi, a, b, delta)
if cover[node] > 0:
covered[node] = ys[hi] - ys[lo]
elif hi - lo == 1:
covered[node] = 0
else:
covered[node] = covered[2 * node] + covered[2 * node + 1]
events = [] # (x, +1 opening / -1 closing, y1, y2)
for x1, y1, x2, y2 in rects:
if x1 < x2 and y1 < y2:
events += [(x1, 1, y1, y2), (x2, -1, y1, y2)]
events.sort()
area, prev_x = 0, None
for x, delta, y1, y2 in events:
if prev_x is not None:
area += covered[1] * (x - prev_x) # covered y-length times the strip width
update(1, 0, segments, index[y1], index[y2], delta)
prev_x = x
return area
print(union_area([(0, 0, 4, 4), (2, 2, 6, 6)])) # 28 (16 + 16 - 4 overlap)
print(union_area([(0, 0, 1, 1), (2, 2, 3, 3)])) # 2
print(union_area([(0, 0, 10, 10), (1, 1, 2, 2)])) # 100 (nested)
print(union_area([])) # 0
How the Sweep Works
Compress the y-coordinates: only the distinct y1 and y2 values matter, so the tree has one leaf per elementary y-interval.
Create two events per rectangle: open at x1 (+1) and close at x2 (−1). Sort them by x.
Between two consecutive event x-values, the covered area equals the covered y-length × the strip width. The root’s covered value holds that length.
Apply each event as a range update on the tree. A node with cover > 0 is fully covered; otherwise its covered length is the sum of its children’s.
For the squares (0, 0)–(4, 4) and (2, 2)–(6, 6), the strips give 4·2 + 6·2 + 4·2 = 28, which is 16 + 16 − 4.
This tree needs no lazy propagation: cover counts are added and removed in matching pairs, so they never need to be pushed down.
Geometry Problems Solved with Segment Trees
Problem
Approach
Time
Area of a union of rectangles (Klee’s measure problem in 2-D)
Sweep + coverage counts (above)
O(n log n)
Perimeter of a union of rectangles
Same sweep, tracking covered length and the number of covered segments
O(n log n)
Counting intersections of horizontal and vertical segments
Sweep over x; a tree (or Fenwick tree) counts the active horizontal segments in a y-range
O(n log n)
Interval stabbing queries
Each interval is stored at O(log n) canonical nodes
O(log n + k) per query, O(n log n) space
Rectangle stabbing, windowing
Segment tree whose nodes hold another structure (multi-level tree)
O(log² n + k)
Data Analysis Uses
Task
Tree stores
Rolling dashboards with late or corrected data
Sum, count or min/max per time bucket, with point updates
“Maximum price between two timestamps”
Range max
Histogram or percentile queries over ranges
Counts per value bucket (or a persistent segment tree for range kth)
Range updates such as “add 5 to every bucket in a window”
Lazy propagation
Complexity of the Example
Sorting events costs O(n log n). Each of the 2n updates touches O(log n) nodes, so the total is O(n log n) time and O(n) space.
Edge Cases and Pitfalls
Degenerate rectangles (zero width or height) are skipped.
Touching edges are handled, because coordinates are half-open.
Large coordinates: compression keeps the tree’s size linear in the number of rectangles.
Floating-point coordinates: compression still works, but accumulate the area carefully.
Recursion depth: O(log n), so it is safe.
Interview Tips
Explain the sweep line plus coverage counts, and why this tree needs no lazy propagation.
Mention coordinate compression.
For data analysis, contrast it with prefix sums (static data) and a Fenwick tree (sums only, less code).
91
Explain how Suffix Trees are utilized in sequence alignment algorithms in bioinformatics.
KnownRevise
In bioinformatics, suffix trees index a DNA or protein sequence so that any substring can be found in time proportional to its length, no matter how long the genome is. Alignment tools use this to find exact matching “seeds” quickly and then extend them with slower dynamic programming (Smith–Waterman or banded alignment). In whole-genome alignment, the original MUMmer used a suffix tree to find maximal unique matches (MUMs) between two genomes. Those MUMs anchor the alignment, and only the gaps between them need detailed alignment. A suffix tree for a human genome needs far more memory than the genome itself, so modern tools usually use its compact relatives: suffix arrays and the FM-index (based on the Burrows–Wheeler transform), as in BWA and Bowtie 2.
Read full answerHide full answer
Applies tobioinformatics algorithms (example in Python 3.12)
Code Example: Seed-and-Extend with a Suffix Array
A suffix array lists the suffixes in sorted order. It supports the same substring searches as a suffix tree, using binary search, and is much smaller.
from bisect import bisect_left, bisect_right
def suffix_array(text: str) -> list[int]:
"""Start positions of all suffixes in sorted order (simple O(n² log n) build for a demo)."""
return sorted(range(len(text)), key=lambda i: text[i:])
def occurrences(text: str, sa: list[int], pattern: str) -> list[int]:
"""All positions of pattern: binary search for the block of suffixes that start with it."""
m = len(pattern)
lo = bisect_left(sa, pattern, key=lambda i: text[i:i + m])
hi = bisect_right(sa, pattern, key=lambda i: text[i:i + m])
return sorted(sa[lo:hi])
def align_read(reference: str, sa: list[int], read: str, k: int = 4, max_mismatches: int = 1):
"""Seed-and-extend: exact k-mer seeds find candidates, then each candidate is checked in full."""
candidates = set()
for offset in range(0, len(read) - k + 1, k): # non-overlapping seeds
for pos in occurrences(reference, sa, read[offset:offset + k]):
start = pos - offset
if 0 <= start <= len(reference) - len(read):
candidates.add(start)
hits = []
for start in sorted(candidates):
mismatches = sum(a != b for a, b in zip(read, reference[start:start + len(read)]))
if mismatches <= max_mismatches:
hits.append((start, mismatches))
return hits
reference = "ACGTTGCAAGGCTTACGTTGCATGGCTA"
sa = suffix_array(reference)
print(occurrences(reference, sa, "ACGTTGCA")) # [0, 14]
print(align_read(reference, sa, "TTGCATGG")) # [(3, 1), (17, 0)]
print(align_read(reference, sa, "GGGGGGGG")) # []
The read TTGCATGG is split into the seeds TTGC and ATGG. TTGC occurs at positions 3 and 17, so the read could start at 3 or 17. Checking each candidate in full gives an exact match at 17 and one mismatch at 3.
Where Suffix Trees and Their Relatives Are Used
Task
Use
Examples
Whole-genome alignment
Find MUMs or maximal exact matches as anchors, then chain them and align the gaps
MUMmer (suffix tree in early versions; MUMmer4 uses a suffix array)
Short-read mapping
Exact seed search over the reference genome
BWA and Bowtie 2 (FM-index)
Repeat finding
Internal nodes with several leaves are repeated substrings
REPuter-style analysis, tandem repeat detection
Motif discovery
Count occurrences of all substrings, with mismatches
Suffix-tree motif finders
Comparing many genomes
Generalized suffix tree: shared substrings across sequences
Pan-genome analysis
Longest common substring
Deepest node with leaves from both sequences
Conserved region detection
Why Seeds Make Alignment Fast
Full dynamic-programming alignment of a read of length m against a genome of length n costs O(m · n). That is impractical for n ≈ 3.1 billion and millions of reads. With an index:
Seed: find exact matches of short substrings in O(seed length) each (suffix tree) or with a few binary-search steps (suffix array, FM-index).
Filter: keep the genome positions supported by enough seeds.
Extend: align the read only around those few positions.
By the pigeonhole principle, a read with at most e mismatches split into e + 1 non-overlapping seeds has at least one exact seed, so this filter cannot miss such matches.
Memory Is the Deciding Factor
Index
Approximate size for a 3.1-billion-base genome
Query
Suffix tree
Tens of gigabytes (commonly 10–20 bytes or more per base)
O(m)
Suffix array (+ LCP)
About 4–8 bytes per base (12–25 GB)
O(m log n), or faster with LCP
FM-index (BWT + sampled suffix array)
A few gigabytes, depending on how densely the suffix array is sampled
O(m) backward search
k-mer hash table (BLAST-style)
Depends on k
O(1) per seed, exact seed length only
That is why suffix trees are mostly used for smaller sequences and for teaching, while production read mappers rely on the FM-index. Newer aligners such as minimap2 use minimizer hash indexes instead.
Complexity
Step
Suffix tree
This demo
Build
O(n) (Ukkonen’s algorithm)
O(n² log n) naive sort of suffixes
Seed lookup
O(k + occurrences)
O(k log n + occurrences)
Extension
O(m) per candidate, more with gaps (DP)
O(m) mismatch count
Edge Cases and Pitfalls
Repeats: seeds in repetitive regions match thousands of places; aligners cap or down-weight them.
Reverse complement: DNA has two strands, so search the read and its reverse complement.
Indels: mismatch counting does not handle insertions or deletions; extension uses gapped DP.
Ambiguous bases (N): usually excluded from seeds.
Interview Tips
Explain seed-and-extend and why exact seeds come from a suffix index.
Mention MUMs in whole-genome alignment.
Point out the memory problem and the move to suffix arrays and the FM-index.
92
Describe the application of trees in Multi-dimensional Searching.
KnownRevise
Multi-dimensional searching means querying points or shapes by several coordinates at once: all restaurants inside a map rectangle, the nearest taxi to a rider, or the closest feature vectors to a query. A one-dimensional index sorts by only one key, so it cannot prune in two or more dimensions. Space-partitioning trees split space recursively and can skip whole regions that cannot contain answers: - k-d trees split on one coordinate per level. - Quadtrees and octrees split a square or cube into 4 or 8 equal parts. - R-trees group nearby objects under bounding rectangles. - Range trees nest one tree inside another.
For low dimensions, these trees give roughly logarithmic nearest-neighbour and range queries.
Read full answerHide full answer
Applies toalgorithms and spatial databases (examples in Python 3.12)
Code Example: k-d Tree with Nearest-Neighbour and Range Search
from __future__ import annotations
import math
from dataclasses import dataclass
Point = tuple[float, ...]
@dataclass
class KDNode:
point: Point
axis: int
left: KDNode | None = None
right: KDNode | None = None
def build(points: list[Point], depth: int = 0) -> KDNode | None:
"""Split on the median of one axis per level, cycling x, y, ...: a balanced tree."""
if not points:
return None
axis = depth % len(points[0])
points = sorted(points, key=lambda p: p[axis])
mid = len(points) // 2
return KDNode(points[mid], axis, build(points[:mid], depth + 1), build(points[mid + 1:], depth + 1))
def nearest(root: KDNode | None, target: Point) -> tuple[Point | None, float]:
"""Nearest neighbour: search the target's side first, cross the split only if it can help."""
best: list = [None, math.inf]
def visit(node: KDNode | None) -> None:
if node is None:
return
d = math.dist(node.point, target)
if d < best[1]:
best[:] = [node.point, d]
diff = target[node.axis] - node.point[node.axis]
near, far = (node.left, node.right) if diff < 0 else (node.right, node.left)
visit(near)
if abs(diff) < best[1]: # the splitting plane is closer than the best so far
visit(far)
visit(root)
return best[0], best[1]
def range_search(root: KDNode | None, low: Point, high: Point) -> list[Point]:
"""All points inside the axis-aligned box [low, high]."""
found, stack = [], [root] if root else []
while stack:
node = stack.pop()
if all(lo <= c <= hi for lo, c, hi in zip(low, node.point, high)):
found.append(node.point)
a = node.axis
if node.left and low[a] <= node.point[a]:
stack.append(node.left)
if node.right and node.point[a] <= high[a]:
stack.append(node.right)
return sorted(found)
stores = [(2, 3), (5, 4), (9, 6), (4, 7), (8, 1), (7, 2)]
tree = build(stores)
print(tree.point) # (7, 2) root: median by x
print(nearest(tree, (9, 2))) # ((8, 1), 1.4142135623730951)
print(range_search(tree, (3, 0), (8, 5))) # [(5, 4), (7, 2), (8, 1)]
How Pruning Works
At each node, the tree splits on one axis, such as x. For a nearest-neighbour query, the search goes down the target’s side first. It crosses to the other side only if the splitting line is closer than the best distance found so far. In the example, the query (9, 2) finds (8, 1) at distance √2 ≈ 1.41, and branches beyond 1.41 from their splitting lines are skipped.
Tree Types
Tree
Splits
Best for
Used in
k-d tree
One coordinate per level, at the median
Static point sets, low dimensions (about 2–10)
scikit-learn KDTree, SciPy cKDTree
Quadtree / octree
Space into 4 (2-D) or 8 (3-D) equal cells
Uneven densities, images, games, maps
Collision detection, map tiles, image compression
R-tree (R*-tree variants)
Groups objects by minimum bounding rectangles
Rectangles and polygons, dynamic inserts, disk storage
O(n log n), or O(n log² n) with this sort-per-level code
O(√n + k) worst case
O(log n) typical, O(n) worst case
Quadtree
O(n log(span))
Depends on data distribution
Typically O(log n)
R-tree
O(n log n) bulk-loaded
O(log n + k) typical, no strong worst-case bound
Typically O(log n)
Range tree (2-D)
O(n log n)
O(log² n + k), or O(log n + k) with fractional cascading
Not its focus
The Curse of Dimensionality
When the number of dimensions grows past roughly 10 to 20, almost every region lies close to the query’s distance boundary. Pruning then stops working, and k-d trees degrade to a near-linear scan. For high-dimensional data, such as text or image embeddings with hundreds of dimensions, systems use approximate nearest-neighbour methods: - HNSW graphs (in FAISS, pgvector and many vector databases) - IVF clustering with product quantization - Random-projection trees (Annoy)
Edge Cases and Pitfalls
Duplicate coordinates: the code puts equal values on either side, so range queries use <= on both sides.
Unbalanced inserts: inserting points one at a time into a k-d tree can unbalance it; rebuild periodically.
Mixed units: scale the axes (kilometres versus seconds) before computing distances.
Points on a sphere: use haversine distance or a spherical index (S2, H3), not planar distance on latitude and longitude.
Interview Tips
Name the tree that fits the data: a k-d tree for points, an R-tree for shapes on disk (PostGIS, map apps), a quadtree or BVH for games and graphics.
Explain pruning in a nearest-neighbour search.
Mention the curse of dimensionality and approximate nearest-neighbour search for embeddings.
93
Discuss Amortized Analysis in the context of splay trees and their operations.
KnownRevise
A splay tree is a self-adjusting BST. After every access, it splays the accessed node to the root using zig, zig-zig and zig-zag rotations. It stores no balance information, and a single operation can cost O(n), for example accessing the deepest node of a chain. Amortized analysis shows that any sequence of m operations costs O((m + n) log n) in total, so the average per operation is O(log n) even though individual operations vary. The standard proof uses a potential function Φ = Σ log₂(size of each node’s subtree). Expensive splays on deep paths shorten that path and lower Φ, which pays for their extra cost.
Read full answerHide full answer
Applies toalgorithm analysis (examples in Python 3.12)
Code Example: Expensive Once, Cheap on Average
from __future__ import annotations
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
def splay(root: Node | None, key: int) -> Node | None:
"""Top-down splay: bring key (or the last node on its search path) to the root."""
if root is None:
return None
header = Node(0) # collects the left and right trees during the descent
left_max = right_min = header
node = root
while True:
if key < node.key:
if node.left is None:
break
if key < node.left.key: # zig-zig: rotate right first
child = node.left
node.left, child.right = child.right, node
node = child
if node.left is None:
break
right_min.left = node # link node into the right tree
right_min = node
node = node.left
elif key > node.key:
if node.right is None:
break
if key > node.right.key: # zag-zag: rotate left first
child = node.right
node.right, child.left = child.left, node
node = child
if node.right is None:
break
left_max.right = node # link node into the left tree
left_max = node
node = node.right
else:
break
left_max.right, right_min.left = node.left, node.right # reassemble
node.left, node.right = header.right, header.left
return node
import math
import random
def depth(root: Node | None, key: int) -> int:
"""Nodes on the search path for key: the actual cost of one access."""
d, node = 0, root
while node:
d += 1
if key == node.key:
break
node = node.left if key < node.key else node.right
return d
n = 1024
root = None
for key in range(n): # each new maximum becomes the root: a left chain
new = Node(key)
new.left, root = root, new
print(depth(root, 0)) # 1024: the first access is very expensive
costs = []
random.seed(7)
for key in [0] + [random.randrange(n) for _ in range(9999)]:
costs.append(depth(root, key))
root = splay(root, key)
print(costs[0], costs[1]) # 1024 183
print(round(sum(costs) / len(costs), 1), round(math.log2(n), 1)) # 12.7 10.0: about log2(n) per access on average
Building the tree by inserting 0 to 1,023 in order creates a chain, so the first access to key 0 visits 1,024 nodes. Splaying that node also folds the chain roughly in half. Over 10,000 accesses, the average is about 12.7 nodes, close to log₂ 1024 = 10.
The Potential Method
Term
Definition
size(x)
Number of nodes in x’s subtree
rank r(x)
log₂ size(x)
Potential Φ
Sum of ranks of all nodes
Amortized cost
Actual cost + ΔΦ
Access lemma (Sleator and Tarjan, 1985): splaying node x in a tree with root t has amortized cost at most 3 (r(t) − r(x)) + 1 = O(log(n / size(x))). Each zig-zig or zig-zag step costs at most 3 (r′(x) − r(x)) amortized, and the sum of those terms telescopes. Only the final single zig adds +1.
Summing over m operations: total actual cost ≤ total amortized cost + Φ(initial) − Φ(final) ≤ m · O(log n) + O(n log n).
Why Zig-Zig Matters
Rotating x to the root one level at a time (simple “move to root”) does not give the logarithmic bound: a chain can stay a chain. A zig-zig step first rotates the parent and then x. This roughly halves the depth of every node on the access path, and that halving is what pays for the expensive access.
Stronger Results
Theorem
Statement
Balance
m accesses cost O((m + n) log n)
Static optimality
Within a constant factor of the best fixed BST for the access frequencies
Working set
Accessing an item recently used is cheap: O(log(number of distinct items since its last access))
Sequential access
Accessing all n keys in sorted order costs O(n) in total
Dynamic optimality
Conjecture, open since 1985: splay trees are within a constant factor of any BST algorithm
Amortized Costs of Operations
Operation
Amortized cost
Worst single operation
Search (with splay)
O(log n)
O(n)
Insert
O(log n)
O(n)
Delete
O(log n)
O(n)
Split, join
O(log n)
O(n)
When Amortized Bounds Are a Problem
Real-time systems need a bound on every operation; use AVL or red-black trees.
Concurrent reads become writes, since every lookup restructures the tree, which hurts caching and locking.
Persistent or shared trees: amortized arguments can break if old versions are reused, because an expensive operation can be repeated.
Common Pitfalls
Saying splay trees are “O(log n) per operation” without amortized.
Confusing amortized with average-case analysis. Amortized bounds hold for every sequence; average-case bounds assume random inputs.
Implementing move-to-root instead of real zig-zig rotations.
Interview Tips
Define amortized: a worst-case bound on the total of any sequence, divided by its length.
Sketch the potential function and the access lemma’s 3(r(t) − r(x)) + 1 bound.
Mention the working-set property and the open dynamic optimality conjecture.
94
Explain how to Optimize Space Complexity in tree algorithms.
KnownRevise
Space in tree algorithms comes from two sources: - Working memory during an algorithm: recursion stacks, queues and temporary lists. - The tree’s representation: pointers, per-node metadata and object overhead.
To reduce working memory, use iterative traversals, O(1)-space techniques such as Morris traversal and in-place rewiring, generators instead of full result lists, and tail recursion on the larger side. To reduce the representation, use implicit arrays for complete trees (heaps), compact node layouts (integer indexes instead of pointers, packed fields), shared subtrees and succinct encodings that store a tree’s shape in about 2 bits per node.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example: Pointer-Free Representations
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
def level_order(root: Node | None) -> list[int]:
out, queue = [], deque([root] if root else [])
while queue:
node = queue.popleft()
out.append(node.val)
queue.extend(c for c in (node.left, node.right) if c)
return out
def encode_shape(root: Node | None) -> str:
"""Shape of a binary tree in 2n + 1 bits: preorder, '1' for a node, '0' for a missing child."""
bits, stack = [], [root]
while stack:
node = stack.pop()
if node is None:
bits.append("0")
continue
bits.append("1")
stack.extend((node.right, node.left))
return "".join(bits)
def decode_shape(bits: str, values: list[int]) -> Node | None:
"""Rebuild the tree from the shape bits plus the values in preorder."""
it_bits, it_vals = iter(bits), iter(values)
if next(it_bits) == "0":
return None
root = Node(next(it_vals))
slots = [(root, "right"), (root, "left")]
for bit in it_bits:
parent, side = slots.pop()
if bit == "1":
child = Node(next(it_vals))
setattr(parent, side, child)
slots.extend(((child, "right"), (child, "left")))
return root
def implicit_children(i: int) -> tuple[int, int]:
"""Complete trees need no pointers at all: children of index i in an array."""
return 2 * i + 1, 2 * i + 2
tree = build([8, 3, 10, 1, 6, None, 14])
shape = encode_shape(tree)
print(shape, len(shape)) # 1110010010100 13 (2n + 1 bits for n = 6)
copy = decode_shape(shape, [8, 3, 1, 6, 10, 14])
print(level_order(copy)) # [8, 3, 10, 1, 6, 14]
heap = [1, 3, 2, 7, 4]
print([heap[c] for c in implicit_children(1) if c < len(heap)]) # [7, 4]
A pointer-based node with two 64-bit pointers spends 128 bits on structure alone. The shape encoding uses 2n + 1 bits for the whole tree, and the values are stored separately in preorder. Heaps go further: a complete tree in an array needs no structural information at all, because the children of index i are 2i + 1 and 2i + 2.
Working-Memory Techniques
Technique
Space saved
Example
Iterative traversal with an explicit stack
Removes recursion-limit risk; same O(h)
DFS, in-order walks
BFS versus DFS choice
BFS holds O(width); DFS holds O(height)
Use DFS on wide trees and BFS on deep, narrow ones
Half the size of 64-bit pointers; better cache use
Manual memory management
Minimal metadata
Red-black trees need 1 colour bit; AVL needs about 2 bits for the balance factor
Packing bits takes care
__slots__ in Python, structs in C or Rust
Avoids per-object dictionaries
Less flexibility
Higher fanout (B-trees)
Fewer pointers per key
Larger nodes to search
Path-compressed tries (radix trees)
Removes single-child chains
More complex updates
Hash-consing (shared identical subtrees)
Repeated subtrees stored once, making a DAG
Nodes must be immutable
Persistent structures
Versions share unchanged subtrees
O(log n) copies per update
Succinct trees (LOUDS, balanced parentheses)
About 2n bits + o(n) for the shape
Navigation needs rank and select support structures
Edge Cases and Pitfalls
Recursion depth: recursive solutions use hidden O(h) stack space. On a skewed tree that is O(n), and it crashes in Python at about 1,000 frames.
Morris traversal temporarily changes the tree, so it is unsafe with concurrent readers.
Premature compaction: succinct structures save memory but are harder to update; use them for static data.
Hidden copies: list slicing in recursive builders (preorder[1:]) copies data at every level, which costs O(n²) in total.
Interview Tips
Ask whether output space counts; many answers are O(1) extra space plus the output.
Mention iterative versus recursive stack usage and Morris traversal.
For representation, mention array-based heaps and the 2n-bit shape encoding.
95
How can you measure and improve the Cache Performance of tree operations?
KnownRevise
Tree operations are often limited by memory latency, not by comparisons. Each step down a pointer-based tree can be a cache miss costing on the order of 100 ns, while a comparison takes about 1 ns. To measure this, use hardware counters (perf stat), cache simulators (Valgrind’s Cachegrind) or profilers such as Intel VTune, and benchmark at realistic data sizes. To improve it: - Put more keys in each cache line (B-trees with node sizes of a few cache lines). - Store nodes contiguously in a layout that matches the access pattern, such as the Eytzinger (BFS) or van Emde Boas layout. - Use smaller nodes (32-bit indexes, keys stored inline) and prefetch the next node.
Read full answerHide full answer
Applies toperformance engineering in C, C++, Rust, Java and Go; layout example in Python 3.12
Code Example: Eytzinger Layout
A sorted array searched with binary search jumps across the whole array. The Eytzinger layout stores the same keys in BFS order of the implicit balanced BST, so the first few levels sit together at the front of the array, and the children of slot k are 2k and 2k + 1.
from bisect import bisect_left
def eytzinger(sorted_keys: list[int]) -> list[int]:
"""Lay out a sorted array in BFS order of the implicit balanced BST (1-based, slot 0 unused)."""
out = [0] * (len(sorted_keys) + 1)
it = iter(sorted_keys)
def fill(k: int) -> None: # in-order walk over implicit node indexes
if k <= len(sorted_keys):
fill(2 * k)
out[k] = next(it)
fill(2 * k + 1)
fill(1)
return out
def lower_bound(layout: list[int], target: int) -> int | None:
"""Smallest key >= target. The top levels sit together at the front of the array."""
k, n = 1, len(layout) - 1
while k <= n:
k = 2 * k + (layout[k] < target) # branch-free step: left or right child
k >>= (~k & (k + 1)).bit_length() # undo the trailing right turns plus one left turn
return layout[k] if k else None
keys = list(range(0, 30, 2)) # 0, 2, ..., 28
layout = eytzinger(keys)
print(layout[1:8]) # [14, 6, 22, 2, 10, 18, 26]
print(lower_bound(layout, 11), lower_bound(layout, 14), lower_bound(layout, 29)) # 12 14 None
assert all(lower_bound(layout, t) == (keys[i] if (i := bisect_left(keys, t)) < len(keys) else None)
for t in range(-2, 32))
print("matches bisect") # matches bisect
In C or C++, this layout combined with prefetching the grandchildren (__builtin_prefetch(&a[16 * k])) is often noticeably faster than std::lower_bound on arrays larger than the cache. Khuong and Morin (2017) studied this in “Array Layouts for Comparison-Based Searching”. In Python, interpreter overhead hides these effects, so measure in a compiled language.
Measuring
Tool
What it shows
perf stat -e cache-misses,cache-references,LLC-load-misses ./bench (Linux)
Hardware cache-miss counts
valgrind --tool=cachegrind ./bench
Simulated misses per source line
Intel VTune or AMD uProf
Memory-bound stalls, hot loads
perf c2c
False sharing between cores
Benchmarks such as Google Benchmark or JMH
Time per operation as the tree grows from L1 size to beyond the L3 cache
Key signal: plot time per lookup against tree size. Sharp steps appear when the working set exceeds each cache level, roughly 32–64 KB for L1, 1–2 MB for L2 and tens of MB for L3.
Improvement Techniques
Technique
Why it helps
B-trees and B+ trees in memory (node of 128–512 bytes)
One or two cache lines hold many keys, so the tree is shallow
Eytzinger or van Emde Boas layout for static data
Nearby levels share cache lines; the van Emde Boas layout is cache-oblivious
Node pools / arenas
Nodes allocated together are near each other in memory
Rebuild in traversal order
Periodically copy nodes into DFS or BFS order
Smaller nodes
32-bit indexes, packed metadata, keys inline instead of pointers to keys
Structure of arrays
Search keys stored separately from rarely used payloads
Prefetching
Hides latency by loading the next node early
Batching queries
Sort the queries; process them together so paths overlap
Avoid false sharing
Pad per-thread counters to separate cache lines
Choosing a Structure
Workload
Cache-friendly choice
Static sorted keys, many lookups
Eytzinger array with prefetching, or a static B-tree
Dynamic ordered map
B-tree (Rust’s BTreeMap, Abseil’s btree_map) instead of a red-black tree
Exact lookups only
Open-addressing hash table
Priority queue
Binary heap in an array, or a 4-ary heap for fewer levels
Rust’s standard BTreeMap uses B-trees rather than red-black trees mainly for cache efficiency, and Abseil offers absl::btree_map as a faster alternative to std::map in many workloads.
Edge Cases and Pitfalls
Benchmarking only small trees that fit in L1 hides the problem.
Garbage collectors may move or scatter objects; Java and Go trees with many small objects pay pointer-chasing costs.
Changing layout invalidates pointers: use indexes when rebuilding into arrays.
Over-large nodes waste time searching inside each node; tune the size by measuring.
Interview Tips
State the core fact: memory latency dominates pointer-based trees.
Name the tools: perf, Cachegrind, VTune.
Recommend B-trees in memory and the Eytzinger layout for static data, with prefetching.
96
Provide strategies for Load Balancing in distributed tree structures.
KnownRevise
Distributed tree structures include range-partitioned key spaces (distributed B-trees in Bigtable, HBase and CockroachDB), hierarchical namespaces (file-system metadata, DNS, ZooKeeper) and aggregation or broadcast trees. They have two typical load problems: - Hot spots: sequential keys, popular subtrees, or the upper levels and root that every request passes through. - Uneven growth: some subtrees become much larger than others.
The main strategies are splitting and merging partitions by size and load, moving or replicating hot partitions, randomising key placement (hashing or salting) when range order is not needed, caching the upper levels on clients so the root is not a bottleneck, and dynamic subtree partitioning for hierarchical namespaces.
Read full answerHide full answer
Applies todistributed systems design
Strategies
Strategy
How it works
Example systems
Size-based splitting
A key range is split when it exceeds a threshold
Bigtable tablets, HBase regions, CockroachDB ranges (512 MiB by default)
Load-based splitting
Split a range that receives too many requests, even if it is small
CockroachDB and Spanner load-based splitting
Merging
Combine small, cold neighbouring ranges
HBase region merges, CockroachDB range merges
Rebalancing replicas
Move ranges or leaders to less loaded nodes
CockroachDB allocator, HBase balancer
Read replicas / follower reads
Spread read load for hot ranges
Spanner and CockroachDB follower reads
Hashing or salting keys
Prefix keys with a hash so sequential writes spread out
HBase salted row keys; hash-sharded indexes
Consistent hashing
Nodes own arcs of a hash ring; virtual nodes even out ownership
Cassandra, DynamoDB-style stores
Client-side caching of upper levels
Clients cache the location tree, so most requests skip the root
Bigtable’s METADATA tablets
Dynamic subtree partitioning
Busy directory subtrees move to other metadata servers
CephFS metadata servers
Hierarchical delegation
Each level is served by different servers; caching at resolvers
Hash or salt the key prefix, use UUIDv4-style random IDs, or use hash-sharded indexes
One very popular key
A single celebrity or product
Cache it, replicate reads, or split the value into several keys (counter sharding)
Root or metadata servers
Every lookup starts at the top
Client caching, replication of the upper levels, leases
A large directory
Millions of files in one folder
Hash the directory across servers (directory fragmentation in CephFS)
Aggregation root
Every leaf reports to one node
Multi-level aggregation trees, sampling
Trade-offs
Choice
Benefit
Cost
Range partitioning
Efficient range scans
Hot spots on sequential keys
Hash partitioning
Even load
Range scans touch every shard
Aggressive splitting
Smooth load
More metadata and more cross-partition transactions
Moving partitions often
Fast reaction
Data movement uses network and disk; caches go cold
Replicating hot data
Read scaling
Write amplification; consistency management
Design Process
Measure: requests per second, bytes and latency per partition, and the distribution of key access.
Choose the partitioning: ranges when range queries matter, hashes when they do not, or a composite key (hash(customer) + timestamp).
Set thresholds for splitting and merging, based on both size and load, with hysteresis so partitions do not flap between states.
Automate movement with rate limits, so rebalancing does not overload the cluster.
Protect the top of the tree with caching and replication.
Monitor imbalance with a metric such as max/mean load per node, and alert on it.
Edge Cases and Pitfalls
Rebalancing storms: many simultaneous moves after a node failure; throttle them.
Split points that do not help: splitting a range at a key that receives all the traffic only moves the hot spot. Split by observed load distribution.
Cross-partition transactions increase as partitions shrink.
Clock-based keys concentrate writes in the newest range even after splits.
Interview Tips
Distinguish range versus hash partitioning and the hot-spot trade-off.
Mention split, merge and move, plus client caching of metadata to protect the root.
Give real examples: Bigtable or HBase regions, CockroachDB ranges, CephFS subtree partitioning.
97
Discuss the Composite Design Pattern and its relationship with tree data structures.
KnownRevise
The Composite pattern (from the “Gang of Four” design patterns book, 1994) lets clients treat individual objects and groups of objects in the same way, through one shared interface. It has three roles: a Component interface, Leaf objects with no children, and Composite objects that hold child components and delegate operations to them. The resulting object structure is a tree: composites are internal nodes, leaves are leaves, and an operation such as size() or render() is a recursive traversal of that tree. Typical uses are file systems, UI widget hierarchies, document structures, scene graphs, organisation charts and abstract syntax trees.
Read full answerHide full answer
Applies toobject-oriented design (examples in Python 3.12)
Code Example
from __future__ import annotations
from abc import ABC, abstractmethod
class Entry(ABC):
"""Component: the interface shared by leaves and containers."""
def __init__(self, name: str) -> None:
self.name = name
@abstractmethod
def size(self) -> int: ...
def render(self, indent: int = 0) -> list[str]:
return [f"{' ' * indent}{self.name} ({self.size()} B)"]
class File(Entry):
"""Leaf: has no children."""
def __init__(self, name: str, size: int) -> None:
super().__init__(name)
self._size = size
def size(self) -> int:
return self._size
class Folder(Entry):
"""Composite: holds children and delegates to them."""
def __init__(self, name: str, *children: Entry) -> None:
super().__init__(name)
self.children = list(children)
def add(self, entry: Entry) -> Folder:
self.children.append(entry)
return self
def size(self) -> int:
return sum(child.size() for child in self.children) # the client never checks the type
def render(self, indent: int = 0) -> list[str]:
lines = super().render(indent)
for child in self.children:
lines += child.render(indent + 1)
return lines
project = Folder("project",
File("README.md", 1200),
Folder("src", File("app.py", 5400), File("util.py", 800)),
Folder("assets"))
project.children[2].add(File("logo.svg", 3100))
print("\n".join(project.render()))
# project (10500 B)
# README.md (1200 B)
# src (6200 B)
# app.py (5400 B)
# util.py (800 B)
# assets (3100 B)
# logo.svg (3100 B)
for entry in (project, project.children[0]):
print(entry.name, entry.size()) # same call for a folder and a file
# project 10500
# README.md 1200
The client calls size() on anything without checking whether it is a file or a folder. A folder’s size() is a post-order traversal: it sums its children first.
Roles Mapped to Tree Terms
Pattern role
Tree term
In the example
Component
Node type
Entry
Leaf
Leaf node
File
Composite
Internal node
Folder
Operation
Traversal
size() (post-order), render() (pre-order)
Client
Caller of traversals
print(entry.size())
Design Decisions
Question
Option A
Option B
Where do add and remove live?
In Component (transparency: uniform API, but leaves must reject them)
Only in Composite (safety: type-checked, but clients sometimes need to know the type)
Parent references?
Store parent for upward navigation (paths, bubbling events)
Omit them for simplicity; derive paths during traversal
Child ordering
A list (ordered, like UI children)
A dictionary by name (fast lookup, like directories)
Caching aggregate results
Cache size() and invalidate up the parent chain on change
Recompute every time
This example chooses safety: only Folder has add.
Real-World Examples
Domain
Component
Composite
Leaf
UI toolkits (Swing, Android Views, the browser DOM)
Component, View, Node
Container, ViewGroup, Element
Button, text node
Graphics and scene graphs
Shape or node
Group
Primitive shape
Compilers
AST node
Block, expression
Literal, identifier
Organisations
Employee
Manager with reports
Individual contributor
Infrastructure as code
Resource
Module
Single resource
Related Patterns
Iterator: walks a composite without exposing its structure.
Visitor: adds new operations (such as export or type checking) without modifying each node class.
Decorator: wraps a component to add behaviour, with the same interface.
Builder: constructs complex composites step by step.
Edge Cases and Pitfalls
Cycles: adding a folder to its own descendant creates an infinite traversal; check ancestry in add.
Deep hierarchies: recursive operations may exceed recursion limits; use iterative traversals for very deep trees.
Over-general components: leaves forced to implement child methods they cannot support (the transparency cost).
Shared children: adding one object to two composites turns the tree into a DAG; aggregates then count it twice.
Expensive aggregates: recomputing size() on large trees for every call; cache it with invalidation.
Interview Tips
Say plainly: “Composite is a tree of objects with a uniform interface.”
Explain the transparency versus safety decision for child-management methods.
Mention Visitor for adding operations and Iterator for traversals.
98
When should one consider using the Decorator Pattern with trees?
KnownRevise
The Decorator pattern wraps an object in another object with the same interface, adding behaviour at runtime without changing the original class. With trees, use it when some nodes, or some subtrees, need extra behaviour, and the choice depends on runtime conditions: caching an expensive subtree’s result, logging or tracing evaluation, access checks, validation, or visual additions such as borders and scrollbars around UI components. Decorators can be stacked, as in Cached(Traced(node)), and the rest of the tree does not notice, because a decorated node is still a valid node. Do not confuse this with Python’s @decorator syntax, which wraps functions. The two share a name and the wrapping idea.
Read full answerHide full answer
Applies toobject-oriented design (examples in Python 3.12)
Code Example: Decorating Nodes of an Expression Tree
from __future__ import annotations
from abc import ABC, abstractmethod
class Expr(ABC):
"""Component interface for an expression tree."""
@abstractmethod
def evaluate(self) -> float: ...
@abstractmethod
def show(self) -> str: ...
class Num(Expr):
def __init__(self, value: float) -> None:
self.value = value
def evaluate(self) -> float:
return self.value
def show(self) -> str:
return str(self.value)
class Add(Expr):
def __init__(self, left: Expr, right: Expr) -> None:
self.left, self.right = left, right
def evaluate(self) -> float:
return self.left.evaluate() + self.right.evaluate()
def show(self) -> str:
return f"({self.left.show()} + {self.right.show()})"
class Mul(Expr):
def __init__(self, left: Expr, right: Expr) -> None:
self.left, self.right = left, right
def evaluate(self) -> float:
return self.left.evaluate() * self.right.evaluate()
def show(self) -> str:
return f"({self.left.show()} * {self.right.show()})"
class Cached(Expr):
"""Decorator: same interface, wraps any node and remembers its value."""
def __init__(self, inner: Expr) -> None:
self.inner, self.calls, self._value = inner, 0, None
def evaluate(self) -> float:
if self._value is None:
self.calls += 1
self._value = self.inner.evaluate()
return self._value
def show(self) -> str:
return self.inner.show()
class Traced(Expr):
"""Decorator: logs every evaluation of the wrapped node."""
def __init__(self, inner: Expr, log: list[str]) -> None:
self.inner, self.log = inner, log
def evaluate(self) -> float:
result = self.inner.evaluate()
self.log.append(f"{self.inner.show()} = {result}")
return result
def show(self) -> str:
return self.inner.show()
log: list[str] = []
shared = Cached(Traced(Mul(Num(3), Num(4)), log)) # expensive subtree used twice
expr = Add(shared, Mul(shared, Num(2)))
print(expr.show()) # ((3 * 4) + ((3 * 4) * 2))
print(expr.evaluate()) # 36
print(shared.calls, log) # 1 ['(3 * 4) = 12']
The shared subtree 3 * 4 appears twice in the expression but is evaluated once. The trace shows exactly one computation. Neither Add, Mul nor Num changed.
When the Decorator Pattern Fits
Situation
Why a decorator works
Only some nodes need the behaviour
Wrap just those nodes; others pay nothing
Behaviour is chosen at runtime (debug mode, user permissions)
Wrap or unwrap without changing classes
Several behaviours combine (cache + trace + timing)
Stack decorators instead of creating subclasses for every combination
You cannot modify the node classes (third-party library)
Wrapping needs no source changes
UI trees need optional visual additions
The classic Gang of Four example: a BorderDecorator around a TextView
When to Use Something Else
Need
Better choice
A new operation across all node types (export, type check)
Visitor, or a method on the base class
The behaviour belongs to every node
Put it in the base class
Controlling access or lazy loading of a subtree
Proxy (structurally similar, but its intent is to control access)
Changing how a node’s children are managed
Change the Composite itself
Wrapping a function (Python @lru_cache, @wraps)
Function decorators, a different mechanism
Decorator Versus Composite
Both have a component interface and delegate to other components. A Composite has many children and combines their results. A Decorator has exactly one wrapped component and adds to its behaviour. In a tree, a decorator acts like a single-child node inserted on an edge.
Identity and type checks break:isinstance(node, Mul) is False for Cached(Mul(...)). Code that inspects node types needs to unwrap decorators or avoid type checks.
Stale caches: if the wrapped subtree can change, the cache must be invalidated; this example assumes an immutable tree.
Deep wrapper chains make debugging and stack traces harder; keep the number of layers small.
Equality and hashing must be defined carefully so a decorated node and the original compare as intended.
Interface drift: every method of the component interface must be forwarded, or decorated nodes behave differently.
Interview Tips
Define it: “same interface, wraps one object, adds behaviour at runtime, stackable.”
Give a tree example: caching or tracing a subtree in an expression tree, or a border around a UI component.
Contrast it with Composite (many children), Proxy (access control) and Visitor (new operations for all node types).
99
Explain the importance of Iterator Pattern in tree traversals.
KnownRevise
The Iterator pattern provides a way to visit the elements of a collection one at a time without exposing its internal structure. For trees, this matters a lot. Callers can write for value in tree and get in-order, pre-order or level-order values without knowing about nodes, stacks or queues. Iteration is lazy: the caller can stop early, and only O(h) or O(w) traversal state is kept instead of a full list of n values. Several traversals can run at the same time, each with its own state. The tree’s representation can also change without breaking callers. Python’s iterator protocol and generators, Java’s Iterator and C++ iterators all implement this pattern, and std::map‘s ordered iteration is the best-known example.
Read full answerHide full answer
Applies tolanguage-independent design (examples in Python 3.12)
Code Example
from __future__ import annotations
from collections import deque
from dataclasses import dataclass
@dataclass
class Node:
val: int
left: Node | None = None
right: Node | None = None
def build(values: list[int | None]) -> Node | None:
"""Build a tree from level-order values, None marking a missing child."""
if not values or values[0] is None:
return None
root = Node(values[0])
queue, i = deque([root]), 1
while queue and i < len(values):
node = queue.popleft()
for side in ("left", "right"):
if i < len(values) and values[i] is not None:
child = Node(values[i])
setattr(node, side, child)
queue.append(child)
i += 1
return root
from collections import deque
from collections.abc import Iterator
class InorderIterator:
"""External iterator: O(h) memory, amortized O(1) per next(), works for any BST size."""
def __init__(self, root: Node | None) -> None:
self._stack: list[Node] = []
self._push_left(root)
def _push_left(self, node: Node | None) -> None:
while node:
self._stack.append(node)
node = node.left
def __iter__(self) -> "InorderIterator":
return self
def __next__(self) -> int:
if not self._stack:
raise StopIteration
node = self._stack.pop()
self._push_left(node.right)
return node.val
def preorder(root: Node | None) -> Iterator[int]:
"""Generator: Python keeps the traversal state between yields."""
stack = [root] if root else []
while stack:
node = stack.pop()
yield node.val
stack.extend(c for c in (node.right, node.left) if c)
def level_order_iter(root: Node | None) -> Iterator[int]:
queue = deque([root] if root else [])
while queue:
node = queue.popleft()
yield node.val
queue.extend(c for c in (node.left, node.right) if c)
bst = build([8, 3, 10, 1, 6, None, 14, None, None, 4, 7])
print(list(InorderIterator(bst))) # [1, 3, 4, 6, 7, 8, 10, 14]
print(list(preorder(bst))) # [8, 3, 1, 6, 4, 7, 10, 14]
print(list(level_order_iter(bst))) # [8, 3, 10, 1, 6, 14, 4, 7]
it = InorderIterator(bst)
print(next(it), next(it)) # 1 3 (lazy: stops whenever the caller stops)
print(next(x for x in InorderIterator(bst) if x > 6)) # 7
Why It Matters for Trees
Benefit
Without an iterator
With an iterator
Memory
Build a full list: O(n)
Keep the traversal state: O(h) for DFS, O(w) for BFS
Early stop
Traverse everything, then search the list
next(...) stops after the first match
Encapsulation
Callers know about nodes and children
Callers see a sequence of values
Several traversal orders
Separate list-building functions
One iterator class or generator per order
Concurrent independent traversals
Hard to manage
Each iterator holds its own stack
Composability
Manual loops
Works with zip, itertools, sum, comprehensions
External Versus Internal Iterators
Kind
Who controls the loop
Example
External
The caller calls next()
InorderIterator, Java Iterator, C++ iterators
Internal
The tree calls a function for each element
tree.for_each(callback), Ruby’s each
Generator
Written like internal code, used like an external iterator
Python yield, C# yield return
External iterators allow merging two trees in sorted order by advancing two in-order iterators side by side, which is hard with internal callbacks.
Complexity of the In-Order Iterator
Operation
Cost
Construction
O(h): push the left spine
next()
Amortized O(1): each node is pushed and popped once over the whole traversal; one call can be O(h)
Memory
O(h)
Full traversal
O(n)
Common Interview Problems Built on Tree Iterators
BST iterator with next() and has_next() in O(h) memory.
Two-sum in a BST: a forward and a reverse in-order iterator moving toward each other.
Merge two BSTs into one sorted list.
Kth smallest: iterate k times.
Flatten a nested list or an n-ary tree lazily.
Edge Cases and Pitfalls
Modifying the tree during iteration: stacks then hold stale nodes. Java’s TreeMap iterators are fail-fast and throw ConcurrentModificationException. Document the behaviour or iterate over a snapshot.
Recursive generators (yield from walk(node.left)) are elegant but use O(h) Python frames and hit recursion limits on deep trees; explicit stacks avoid that.
Exhausted iterators: a Python iterator can be used once; create a new one, or make the tree iterable (return a fresh iterator from __iter__).
Parent-pointer iterators (used in C++ std::map) need no stack but require every node to keep a correct parent pointer.
Interview Tips
Explain the three benefits: encapsulation, laziness and O(h) memory.
Implement the stack-based in-order iterator and justify the amortized O(1)next().
Mention fail-fast behaviour on concurrent modification.
100
Discuss Best Practices in implementing tree data structures to avoid common pitfalls.
KnownRevise
Most tree bugs come from a small set of causes: - broken invariants: ordering, balance, or stale heights and sizes; - pointer mistakes: lost subtrees, parent pointers not updated, cycles; - edge cases: empty trees, single nodes, duplicates, skewed shapes; - recursion depth on deep trees; - unclear definitions: height in edges or nodes, how duplicates are handled.
The best practices are to prefer a well-tested library when one fits, to write down the invariants and check them in tests, to use iterative algorithms where trees can be deep, to choose a balanced structure when the input order is not controlled, and to test against a simple reference model with randomised inputs.
Read full answerHide full answer
Applies tolanguage-independent (examples in Python 3.12)
Code Example: Randomised Testing Against a Reference
from __future__ import annotations
import random
from dataclasses import dataclass
@dataclass
class Node:
key: int
left: Node | None = None
right: Node | None = None
class BST:
def __init__(self) -> None:
self.root: Node | None = None
def insert(self, key: int) -> None:
"""Iterative insert; duplicates ignored (a documented rule)."""
if self.root is None:
self.root = Node(key)
return
node = self.root
while True:
if key == node.key:
return
side = "left" if key < node.key else "right"
child = getattr(node, side)
if child is None:
setattr(node, side, Node(key))
return
node = child
def __contains__(self, key: int) -> bool:
node = self.root
while node and node.key != key:
node = node.left if key < node.key else node.right
return node is not None
def keys(self) -> list[int]:
out, stack, node = [], [], self.root
while stack or node:
while node:
stack.append(node)
node = node.left
node = stack.pop()
out.append(node.key)
node = node.right
return out
random.seed(42)
for trial in range(500): # compare with a set: the reference model
tree, model = BST(), set()
for _ in range(random.randint(0, 50)):
key = random.randint(0, 30)
tree.insert(key)
model.add(key)
probe = random.randint(0, 30)
assert (probe in tree) == (probe in model)
assert tree.keys() == sorted(model) # in-order invariant
chain = BST()
for key in range(2_000): # sorted input: a 2,000-deep chain
chain.insert(key)
print(len(chain.keys()), 1_999 in chain) # 2000 True (iterative code survives the depth)
print("all checks passed") # all checks passed
Best Practices
Area
Practice
Reuse
Use std::map, TreeMap, BTreeMap, sortedcontainers or a database index unless you need custom behaviour
Definitions
Document height convention, duplicate rule, comparator and whether the tree may be modified
Invariants
Write them down (BST order, balance, stored sizes) and add an O(n) checker for tests
Balancing
Use a self-balancing tree when inputs may be sorted or adversarial
Iteration
Prefer explicit stacks or queues; recursion depth on skewed trees crashes Python at about 1,000 frames
Pointer updates
Update child, parent and augmented fields (height, size, max-end) together, especially in rotations
Null handling
Test empty trees, single nodes and missing children first
Comparators
Must define a strict weak ordering; inconsistent comparators corrupt trees
Mutability
Do not change a key while the node is in the tree; remove and reinsert
Concurrency
Protect with locks or use concurrent or persistent structures; document iterator behaviour
Memory
Avoid copying in recursion (list[1:] slices); free or pool nodes in manual-memory languages
Serialization
Use an unambiguous format with null markers, and version it
Testing Checklist
Empty tree, one node, two nodes (left and right), duplicates, negative numbers and extreme values.
Sorted, reverse-sorted and random insertion orders.
Deep trees (100,000 nodes in a chain) to catch recursion-depth bugs.
Randomised tests against a reference model such as a set, a sorted list or a brute-force function, as shown above.
Invariant checker after every operation in tests.
Deleting nodes with zero, one and two children, and deleting the root.
Common Pitfalls
Pitfall
Consequence
Fix
Checking a BST node only against its children
Accepts invalid trees
Pass bounds down
Stale augmented data after rotations
Wrong sizes, heights and balance decisions
Recompute bottom-up in every rotation
Overwriting a pointer before saving it
Lost subtree
Use tuple assignment or temporary variables
Recursion on unbounded depth
Stack overflow
Iterative algorithms or balanced trees
Mixing node identity and value equality
Wrong LCA or lookup with duplicate values
Compare nodes with is where identity matters
Leaving Morris threads after an early exit
Corrupted tree
Always finish or clean up
Shared subtrees in a mutable tree
Changes appear in two places
Copy, or use immutable persistent nodes
Interview Tips
Start any tree problem by asking about duplicates, size and depth, balance and mutability.
Mention invariants and an invariant checker.
Describe randomised testing against a simple model; it finds most tree bugs quickly.