Skip to content
DSA Patterns
Menu
Language
Tree DFSLC #1043 of 6← PreviousNext →

Demo preview: These solutions pass the automated test suite but have not been human-reviewed. Treat trade-offs and prose as draft.

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

Unverified
Time O(n)Space O(h)

Idea. 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.

Solution
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.
Contributor review checklist

Interactive

Mental model

A worked animation for this problem. Scrub steps or press space to pause; re-tell the invariant out loud.

Step 1 of 8
1/8

Tree DFS walks structure, not a flat list. Root 3, left 9, right subtree 20 → 15, 7.

3920157
Statenode=3order=post-order

post-order: children first, then me

Key:CurrentActive rangeMatchSettled