Skip to content
DSA Patterns
Menu
Language

Pattern #16

Tree DFS

Essential

Define what each subtree returns to its parent.

When to use

Binary tree answers that combine left and right results: depth, validity, LCA, path sums.

Recognition cues

  • Max depth / balanced tree
  • Validate BST / LCA
  • Path sum variants

Common pitfalls

  • Mixing global answer updates with return values carelessly
  • BST validation with wrong bounds
  • Not handling null children as base case

90-second recognition drill

Which pattern fits best?

  • Max depth / balanced tree
  • Validate BST / LCA
  • Path sum variants

Interactive

Mental model

A full worked walkthrough of the invariant. Pause, scrub the dots, or use ← →. Aim to narrate each step yourself.

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

How to think about it

Write a function f(node) that returns what the parent needs (height, is-BST flag, min/max, best path through node). Solve left and right first, then combine. Sometimes also update a global best.

The interactive mental model draws the actual tree (edges + nodes), not a flat list: watch values and badges (heights, LCA markers) flow up the structure.

Template shapes

Shape What the parent receives Example
BST bounds Null is valid. The node must sit strictly between low and high. The left child gets (low, val) and the right gets (val, high) LC 98
Same tree Two nulls match. One null fails. Otherwise the values match and both child pairs match LC 100
Depth Null is 0. Any other node returns 1 + max(left, right) LC 104
Balance Null returns height 0. A child height of -1, or a height gap greater than 1, returns -1. Otherwise the height is 1 + max(left, right). Balanced means the root height is ≥ 0 LC 110
Max path The value sent upward is val + max(leftGain, rightGain, 0). A bend through the node updates a global best. The parent receives one chain LC 124
LCA Null returns null. A node that is p or q returns itself. Both children returning a witness means this node is the LCA. One witness continues upward LC 236

Complexity baseline

O(n) time visits each node once; space O(h) recursion stack.

From template to problem

  1. Write the return in one sentence before the recursion. Depth returns a height (LC 104). The max path returns one downward chain and hides the bend in a global (LC 124).
  2. Null is the base. Two nulls match for equality (LC 100). A null ancestor is not an LCA witness (LC 236).
  3. BST bounds travel down, not up. The parent tightens the interval before the child call (LC 98).
  4. Balance can ride inside the height: -1 means already unbalanced, so one walk returns both answers (LC 110).

Template

Same skeleton in TypeScript, Python, and C#. Adapt the invariant; keep the structure.

Tree DFS · Template
Show helper code
/** Tree DFS template: max depth. */
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;
  }
}
/** Tree DFS template: max depth. */
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 function maxDepth(root: TreeNode | null): number {
  if (!root) return 0;
  return 1 + Math.max(maxDepth(root.left), maxDepth(root.right));
}