ReviseAlgo Logo
MediumVery High Frequency35 min

Tree DFS (Depth-First Search)

Recursive and iterative DFS for path sums, diameter, max depth, and subtree problems.

Tree DFS explores depth-first. Pre/In/Post-order. Use DFS for path problems, subtree problems, and anything requiring full exploration before returning.

Tree DFS

Traversals — Step by Step

Path Sum II (DFS + Backtrack)

O(n²)O(n) nodes × O(n) path copy per leaf = O(n²) time. O(n) recursion space.
Step-by-step1 / 9
Treelevel links
visit54811613472
1. 5

root=5, remaining=22. Add 5.

Target=22. Visit root=5. path=[5], remaining=17. Go deeper.