Trees
A family tree spans as many generations as its longest branch. Each person asks their children how far down their lines run, then adds one for themselves. The root learns the whole height without ever seeing it.
2 · Watch
Trees in 60 seconds
3 · Now you drive
Maximum Depth of Binary Tree
4 · Your turn
Start from this
function dfs(node: TreeNode | null): number {
// Empty node: the smallest case, answer it directly.
if (!node) return 0;
// Trust each call to solve its own subtree.
const left = dfs(node.left);
const right = dfs(node.right);
// Build this node's answer from its children's.
return combine(node, left, right);
}Easy ways to go wrong
- Leaving out the empty-node base case.
- Checking a node against its parent only. BST rules cover the whole subtree.
- Mixing up what a call returns with the answer you’re tracking.
- Easy01
Invert Binary Tree
Warm-up: swap each node’s children, top down.
Handle one node and let recursion do the rest.
- Time
- O(n)
- Space
- O(h)
- Easy02
Maximum Depth of Binary Tree
The one you just watched. Write it from memory.
My depth is one more than my deepest child.
- Time
- O(n)
- Space
- O(h)
- Easy03
Same Tree
Walk both trees together; every pair must match.
Walk both at once. One mismatch ends it.
- Time
- O(n)
- Space
- O(h)
- Easy04
Subtree of Another Tree
Same-tree check, tried at every node.
Run the same-tree check from every node.
- Time
- O(n·m)
- Space
- O(h)
- Medium05
Lowest Common Ancestor of a Binary Search Tree
Split point where the targets part ways.
Walk down until the two values fall on different sides, or you land on one of them.
- Time
- O(h)
- Space
- O(1)
- Medium06
Binary Tree Level Order Traversal
A queue walks the tree one level at a time.
A queue hands you each level in turn.
- Time
- O(n)
- Space
- O(n)
Also works with Graphs.
- Medium07
Validate Binary Search Tree
Each node inherits a valid range from above.
Pass an allowed range down as you go.
- Time
- O(n)
- Space
- O(h)
- Medium08
Kth Smallest Element in a BST
In-order walk, counting until you reach k.
An in-order walk visits values in sorted order.
- Time
- O(h + k)
- Space
- O(h)
Also works with Heaps.
- Medium09
Construct Binary Tree from Preorder and Inorder Traversal
The preorder head splits the inorder list.
Preorder names the root. Inorder splits left from right.
- Time
- O(n)
- Space
- O(n)
- Hard10
Binary Tree Maximum Path Sum
Like depth, but the best path may bend.
Each node passes up its best straight arm and scores its best bend.
- Time
- O(n)
- Space
- O(h)
- Hard11
Serialize and Deserialize Binary Tree
Level order out, level order back in.
Walk it and write down the gaps too.
- Time
- O(n)
- Space
- O(n)