Back to Roadmap
Week 4Day 22 of 35

DFS on Trees

Go as deep as possible before coming back, usually with recursion.

Day Progress0%

0 of 4 problems solved

Pattern Focus

DFS on Trees

Go as deep as possible before coming back, usually with recursion.

Pattern Checklist
  • Am I supposed to go as deep as possible before returning?
  • Would recursion naturally process left and right children?
  • Do I know what each recursive call should return?
🌳New to DSA? Start here 🧠

Depth First Search on trees means you follow one path as far as it goes before you come back. Recursion is a natural match because each node can ask the same question of its left child and right child. For max depth, you ask, 'How deep is my left side? How deep is my right side?' Then the current node adds one for itself.

Trees get easier when every node solves the same small subproblem for its children.

How to think about it
  1. 1Handle the base case: an empty node contributes zero depth.
  2. 2Recursively compute the left depth and right depth.
  3. 3Take the larger one.
  4. 4Add one for the current node.
🚧Common Mistake

Forgetting the base case for null nodes makes recursion crash or return the wrong depth.

🔍Problem Hints

Construct Binary Tree from Preorder and Inorder Traversal

The first element of preorder is always the root. Locate it in inorder to split left and right subtree sizes. Recurse with matching slices.

Binary Tree Maximum Path Sum

Post-order DFS. leftGain = max(0, dfs(left)), same for right. Update global max with node + leftGain + rightGain. Return only the larger single-branch gain up.

Problems

Maximum Depth of Binary Tree

easy

Invert Binary Tree

easy

Construct Binary Tree from Preorder and Inorder Traversal

medium

Binary Tree Maximum Path Sum

hard