Lesson 136 of 296
Trees: depth-first search
What you will learn
- Tree vocabulary
- Binary trees in TypeScript
- Pre-order, in-order and post-order traversal
- DFS with recursion and with an explicit stack
- Maximum Depth, Invert Tree, Same Tree, Diameter, Balanced Tree
On this page
What is a tree?
A tree is a structure of nodes connected by edges, with no cycles. One node is the root. Each node can have children. A node with no children is a leaf.
A binary tree is a tree where each node has at most two children: left and right.
| Word | Meaning |
|---|---|
| Root | The top node |
| Parent / child | A node and the nodes directly below it |
| Leaf | A node with no children |
| Depth of a node | Number of edges from the root to it |
| Height of a tree | The longest path from the root to a leaf |
| Subtree | A node and everything below it |
Trees are everywhere: the DOM (Lesson 87), file systems, JSON data, organisation charts, React's component tree.
Binary tree nodes
class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val: number, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
function treeFromArray(values: (number | null)[]): TreeNode | null {
if (values.length === 0 || values[0] === null || values[0] === undefined) return null;
const root = new TreeNode(values[0]);
const queue: TreeNode[] = [root];
let i = 1;
let head = 0;
while (head < queue.length && i < values.length) {
const node = queue[head++]!;
const leftValue = values[i++];
if (leftValue !== null && leftValue !== undefined) {
node.left = new TreeNode(leftValue);
queue.push(node.left);
}
const rightValue = values[i++];
if (rightValue !== null && rightValue !== undefined) {
node.right = new TreeNode(rightValue);
queue.push(node.right);
}
}
return root;
}treeFromArray builds a tree from LeetCode's level-order format, such as [3, 9, 20, null, null, 15, 7], which is useful for testing.
Depth-first search (DFS)
DFS goes as deep as possible down one branch before coming back. With recursion, it is natural: handle the node, then recurse into its children.
The three orders differ only in when you visit the node itself:
| Order | Sequence | Use |
|---|---|---|
| Pre-order | Node, left, right | Copying a tree, serialising it |
| In-order | Left, node, right | Sorted order in a binary search tree (Lesson 138) |
| Post-order | Left, right, node | When a node needs its children's answers first (height, deleting) |
function preorder(root: TreeNode | null, out: number[] = []): number[] {
if (root === null) return out;
out.push(root.val);
preorder(root.left, out);
preorder(root.right, out);
return out;
}
function inorder(root: TreeNode | null, out: number[] = []): number[] {
if (root === null) return out;
inorder(root.left, out);
out.push(root.val);
inorder(root.right, out);
return out;
}
function postorder(root: TreeNode | null, out: number[] = []): number[] {
if (root === null) return out;
postorder(root.left, out);
postorder(root.right, out);
out.push(root.val);
return out;
}For the tree
1
/ \
2 3
/ \
4 5pre-order: 1 2 4 5 3; in-order: 4 2 5 1 3; post-order: 4 5 2 3 1.
DFS with an explicit stack
Interviewers sometimes ask for the iterative version (and it avoids stack overflow on very deep trees). In-order with a stack:
function inorderIterative(root: TreeNode | null): number[] {
const result: number[] = [];
const stack: TreeNode[] = [];
let node = root;
while (node !== null || stack.length > 0) {
while (node !== null) {
stack.push(node);
node = node.left;
}
node = stack.pop()!;
result.push(node.val);
node = node.right;
}
return result;
}Go left as far as possible, pushing nodes; pop one, visit it, then move to its right child.
Maximum Depth of Binary Tree
Problem (LeetCode 104): the number of nodes on the longest path from root to leaf.
function maxDepth(root: TreeNode | null): number {
if (root === null) return 0;
return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}A perfect example of "trust the recursion": the depth of a tree is 1 plus the depth of its deeper subtree. O(n) time, O(h) space where h is the height.
Invert Binary Tree
Problem (LeetCode 226): mirror the tree (swap every left and right child).
function invertTree(root: TreeNode | null): TreeNode | null {
if (root === null) return null;
const left = invertTree(root.left);
root.left = invertTree(root.right);
root.right = left;
return root;
}Same Tree
Problem (LeetCode 100): are two trees identical in shape and values?
function isSameTree(p: TreeNode | null, q: TreeNode | null): boolean {
if (p === null && q === null) return true;
if (p === null || q === null || p.val !== q.val) return false;
return isSameTree(p.left, q.left) && isSameTree(p.right, q.right);
}Diameter of Binary Tree
Problem (LeetCode 543): the length (number of edges) of the longest path between any two nodes. It may not pass through the root.
Idea: at each node, the longest path through it = height of left subtree + height of right subtree. Compute heights with post-order DFS, and update a best answer along the way.
function diameterOfBinaryTree(root: TreeNode | null): number {
let best = 0;
function height(node: TreeNode | null): number {
if (node === null) return 0;
const left = height(node.left);
const right = height(node.right);
best = Math.max(best, left + right);
return 1 + Math.max(left, right);
}
height(root);
return best;
}This "return one thing, track another in an outer variable" trick is very common in tree problems.
Balanced Binary Tree
Problem (LeetCode 110): is the tree height-balanced (at every node, the heights of the two subtrees differ by at most 1)?
function isBalanced(root: TreeNode | null): boolean {
function checkHeight(node: TreeNode | null): number {
if (node === null) return 0;
const left = checkHeight(node.left);
if (left === -1) return -1;
const right = checkHeight(node.right);
if (right === -1) return -1;
if (Math.abs(left - right) > 1) return -1;
return 1 + Math.max(left, right);
}
return checkHeight(root) !== -1;
}Returning -1 as a "not balanced" signal stops early and keeps it O(n). (Checking balance separately at each node would be O(n²).)
How to say it in an interview
"DFS explores one branch fully before backtracking. With recursion, pre-order visits the node before its children, in-order between them, and post-order after them; post-order suits problems where a node needs its children's results, like height or diameter. I can also write DFS iteratively with a stack to avoid deep recursion. For diameter and balance I compute heights bottom-up and track the answer in an outer variable or a sentinel value, keeping it O(n) time and O(height) space."
Key words
| Word | Meaning |
|---|---|
| Tree | Nodes connected without cycles, with one root |
| Binary tree | Each node has at most two children |
| Leaf | A node with no children |
| Height | The longest root-to-leaf path |
| DFS | Depth-first search: go deep first |
| Pre / in / post-order | When the node is visited relative to its children |
Now prove it
This lesson is complete when you pass the quiz and all three practice levels.