Trees & Traversals
Hierarchical data — terminology, binary trees, and the four traversals every engineer must know cold.
A tree is a hierarchy of nodes connected by edges, with one root and no cycles. File systems, the HTML DOM, org charts, JSON, abstract syntax trees, database indexes and decision trees are all trees.
Vocabulary
| Term | Meaning |
|---|---|
| Root | The top node (no parent) |
| Parent / child | Directly connected nodes, one level apart |
| Leaf | A node with no children |
| Subtree | A node plus all its descendants |
| Depth of a node | Edges from the root to it (root depth = 0) |
| Height of a node | Edges on the longest path down to a leaf |
| Degree | Number of children |
A tree with n nodes always has exactly n − 1 edges.
Binary trees
Each node has at most two children: left and right.
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) { this.val = val; }
}class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = rightclass TreeNode {
constructor(
public val: number,
public left: TreeNode | null = null,
public right: TreeNode | null = null,
) {}
}Shapes worth naming
- Full — every node has 0 or 2 children.
- Complete — every level full except possibly the last, which fills left to right. Heaps are complete, so they fit in an array.
- Perfect — all internal nodes have 2 children and all leaves share a depth:
2^(h+1) − 1nodes. - Balanced — subtree heights differ by a small amount everywhere → height O(log n).
- Degenerate — every node has one child; really a linked list with height n − 1.
The four traversals
| Traversal | Order | Result | Typical use |
|---|---|---|---|
| Pre-order | node, left, right | 1 2 4 5 3 6 | Copy / serialize a tree |
| In-order | left, node, right | 4 2 5 1 3 6 | BST → sorted order |
| Post-order | left, right, node | 4 5 2 6 3 1 | Delete a tree, compute sizes/heights |
| Level-order (BFS) | level by level | 1 2 3 4 5 6 | Shortest path, level views |
Pre/in/post-order are depth-first. Recursive versions are three lines; the only difference is where you visit the node.
void preorder(TreeNode n, List<Integer> out) {
if (n == null) return;
out.add(n.val); // visit BEFORE children
preorder(n.left, out);
preorder(n.right, out);
}
void inorder(TreeNode n, List<Integer> out) {
if (n == null) return;
inorder(n.left, out);
out.add(n.val); // visit BETWEEN children
inorder(n.right, out);
}
// Iterative in-order with an explicit stack
List<Integer> inorderIter(TreeNode root) {
List<Integer> out = new ArrayList<>();
Deque<TreeNode> st = new ArrayDeque<>();
TreeNode cur = root;
while (cur != null || !st.isEmpty()) {
while (cur != null) { st.push(cur); cur = cur.left; }
cur = st.pop();
out.add(cur.val);
cur = cur.right;
}
return out;
}
List<List<Integer>> levelOrder(TreeNode root) {
List<List<Integer>> res = new ArrayList<>();
Queue<TreeNode> q = new ArrayDeque<>();
if (root != null) q.offer(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int i = q.size(); i > 0; i--) { // exactly one level
TreeNode n = q.poll();
level.add(n.val);
if (n.left != null) q.offer(n.left);
if (n.right != null) q.offer(n.right);
}
res.add(level);
}
return res;
}from collections import deque
def preorder(n, out):
if not n: return
out.append(n.val) # visit BEFORE children
preorder(n.left, out)
preorder(n.right, out)
def inorder(n, out):
if not n: return
inorder(n.left, out)
out.append(n.val) # visit BETWEEN children
inorder(n.right, out)
def inorder_iter(root):
out, st, cur = [], [], root
while cur or st:
while cur:
st.append(cur)
cur = cur.left
cur = st.pop()
out.append(cur.val)
cur = cur.right
return out
def level_order(root):
res, q = [], deque([root] if root else [])
while q:
level = []
for _ in range(len(q)): # exactly one level
n = q.popleft()
level.append(n.val)
if n.left: q.append(n.left)
if n.right: q.append(n.right)
res.append(level)
return resfunction preorder(n: TreeNode | null, out: number[]) {
if (!n) return;
out.push(n.val); // visit BEFORE children
preorder(n.left, out);
preorder(n.right, out);
}
function inorder(n: TreeNode | null, out: number[]) {
if (!n) return;
inorder(n.left, out);
out.push(n.val); // visit BETWEEN children
inorder(n.right, out);
}
function inorderIter(root: TreeNode | null): number[] {
const out: number[] = [], st: TreeNode[] = [];
let cur = root;
while (cur || st.length) {
while (cur) { st.push(cur); cur = cur.left; }
cur = st.pop()!;
out.push(cur.val);
cur = cur.right;
}
return out;
}
function levelOrder(root: TreeNode | null): number[][] {
const res: number[][] = [];
let q = root ? [root] : [];
while (q.length) {
res.push(q.map((n) => n.val));
q = q.flatMap((n) => [n.left, n.right].filter((x): x is TreeNode => x !== null));
}
return res;
}All traversals are O(n) time. Space is O(h) for DFS (recursion/stack depth) and O(w) for BFS (the widest level).
Thinking recursively about trees
Most tree problems follow one recipe: solve for the left subtree, solve for the right subtree, combine with the current node.
int height(TreeNode n) {
if (n == null) return 0; // counts nodes; use -1 to count edges
return 1 + Math.max(height(n.left), height(n.right));
}
int best = 0;
int diameterOfBinaryTree(TreeNode root) { depth(root); return best; }
int depth(TreeNode n) {
if (n == null) return 0;
int l = depth(n.left), r = depth(n.right);
best = Math.max(best, l + r); // longest path THROUGH n
return 1 + Math.max(l, r); // longest path DOWN from n
}def height(n):
if not n: return 0
return 1 + max(height(n.left), height(n.right))
def diameter(root):
best = 0
def depth(n):
nonlocal best
if not n: return 0
l, r = depth(n.left), depth(n.right)
best = max(best, l + r) # path through n
return 1 + max(l, r) # path down from n
depth(root)
return bestfunction height(n: TreeNode | null): number {
return n ? 1 + Math.max(height(n.left), height(n.right)) : 0;
}
function diameter(root: TreeNode | null): number {
let best = 0;
const depth = (n: TreeNode | null): number => {
if (!n) return 0;
const l = depth(n.left), r = depth(n.right);
best = Math.max(best, l + r);
return 1 + Math.max(l, r);
};
depth(root);
return best;
}- Trees are acyclic hierarchies; n nodes ⇒ n − 1 edges.
- Know pre/in/post-order (DFS) and level-order (BFS), recursively and iteratively.
- Traversals are O(n) time; DFS space is O(height), BFS space is O(width).
- Solve tree problems by combining answers from subtrees.
QCan you rebuild a binary tree from its traversals?medium
Pre-order + in-order (or post-order + in-order) uniquely determine a tree with distinct values: the first pre-order element is the root; its position in the in-order sequence splits the left and right subtrees. Use a value→index map for O(n). Pre-order + post-order alone are ambiguous.
QFind the lowest common ancestor of two nodes in a binary tree.medium
Recurse: if the node is null or equals p or q, return it. Recurse left and right; if both return non-null, this node is the LCA; otherwise return whichever is non-null. O(n).
QHow do you traverse a tree in O(1) extra space?hard
Morris traversal: temporarily point the in-order predecessor's right pointer back to the current node ("threading"), walk down, and remove the thread on the second visit. O(n) time, O(1) space, and the tree is restored.