Maximum Depth of Binary Tree
Problem (restated)
Given the root of a binary tree, return its maximum depth (number of nodes along the longest root-to-leaf path).
Intuition
Depth(node) = 1 + max(depth(left), depth(right)); empty node has depth 0. Iterative DFS carries this depth down a stack instead of recursing.
Approaches
Iterative DFS
UnverifiedIdea. Push (node, depth) pairs onto a stack; update the answer at each pop and push children with depth + 1.
Walkthrough. Balanced tree of height 3 → answer 3.
Trade-offs. BFS level-count is equivalent; the iterative stack holds only the current path.
Show helper code
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
export class TreeNode {
val: number;
left: TreeNode | null;
right: TreeNode | null;
constructor(val = 0, left: TreeNode | null = null, right: TreeNode | null = null) {
this.val = val;
this.left = left;
this.right = right;
}
}
export function maxDepth(root: TreeNode | null): number {
let best = 0;
const stack: Array<[TreeNode, number]> = root ? [[root, 1]] : [];
while (stack.length) {
const [node, depth] = stack.pop()!;
best = Math.max(best, depth);
if (node.left) stack.push([node.left, depth + 1]);
if (node.right) stack.push([node.right, depth + 1]);
}
return best;
}
export function maxDepth(root: TreeNode | null): number {
let best = 0;
const stack: Array<[TreeNode, number]> = root ? [[root, 1]] : [];
while (stack.length) {
const [node, depth] = stack.pop()!;
best = Math.max(best, depth);
if (node.left) stack.push([node.left, depth + 1]);
if (node.right) stack.push([node.right, depth + 1]);
}
return best;
}
Template connection
Null is depth 0. Every child is pushed with depth + 1; the answer is the largest depth seen.
Reflection
- Null has depth 0. A leaf is 1. Each stack frame carries its depth; the answer is the maximum.
- A chain leaning to one side has depth
n. A balanced tree is about log n. - An empty tree is 0. Counting BFS layers gives the same number.