Skip to content

Problem-Solving Approach


Look for these keywords in problem statements:

  • “Binary tree”, “BST”, “root”, “leaves”, “path”
  • “Ancestor”, “descendant”, “subtree”
  • “Level”, “depth”, “height”, “width”
  • “Maximum/minimum path”, “diameter”

Use DFS When…Use BFS When…
Computing height/depthLevel-by-level processing
Path sum / root-to-leaf pathsFinding shortest path
Subtree problems (is mirror, same tree, etc.)Right/left view of tree
LCA, diameter, balanced checksZigzag traversal, level averages
Tree serialization/deserializationConnect next pointers level-by-level

There are 3 types of recursive approaches for trees:

→ Compute something at each node using children's results
→ Example: height, diameter, path sums
→ Carry information from parent to children
→ Example: path sum (carry remaining target down)

Pattern 3: Use external state (global variable)

Section titled “Pattern 3: Use external state (global variable)”
→ Maintain a result variable outside recursion, update inside
→ Example: diameter, max path sum

Edge CaseWhat to check
root === nullHandle empty tree; return appropriate default (0, [], null)
Single node treeLeaf node is both root, left, and right boundary
Skewed tree (all left or right)Don’t assume O(log N) depth; stack may overflow
Negative values in nodesPath sum with all negatives; don’t discard negative paths
Duplicate values in BSTClarify how duplicates are handled (left or right subtree)
Integer overflowSum of path may exceed Number.MAX_SAFE_INTEGER in JS

Hard problems often combine multiple basic techniques:

"Max Path Sum" = DFS returning gain + global max tracking
"Serialize/Deserialize" = Preorder + Queue reconstruction
"Cameras on Tree" = Greedy postorder with state propagation
"Vertical Order" = BFS + sort by (col, row, val)