Skip to content
ΣDSA Patterns
Menu
Language

Tree DFS

Guide 3 of 6 · Path 3 of 6

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
3920157

post-order: children first, then me

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

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.

Approaches

Recursive DFS

Tested only
Time O(n)Space O(h)

Idea. Base null→0; return 1+max of children.

Walkthrough. Balanced tree of height 3 → answer 3.

Trade-offs. BFS level-count is equivalent; DFS is shortest to write.

Solution
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 {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.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 {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}

Template connection

Tree DFS returning aggregated info to parent.

Reflection