~/problems
Problems
Basics first, then the classics, then company-style assessments. Every problem has tests you run right here; multi-level ones unlock as you go. See the roadmap.
Tree DP
Post-order: each node returns a small tuple of states to its parent.
Notes
Recognise it when: you're optimizing over a tree with choices per node (take or skip, place a camera or not) or paths through nodes.
def dfs(node): # returns (best if robbed, best if not)
if not node: return (0, 0)
l, r = dfs(node.left), dfs(node.right)
rob = node.val + l[1] + r[1]
skip = max(l) + max(r)
return (rob, skip)
Maximum path sum: return the best downward path (never negative, so clamp at 0), and keep a global best of node + left + right.
Gotchas: separate "what I return to my parent" from "what I record as the answer". Watch the recursion depth.
10 problems
Interview roadmap
Trees Traversals, BSTs, and answers built bottom-up.
Tree DP guide
- Basics: Diameter of a tree basics py · c++ · java easy
- Pruning a diseased fruit tree py · c++ · java easy
- House Robber III py · c++ · java medium
- Binary Tree Maximum Path Sum py · c++ · java medium
- Binary tree cameras py · c++ · java hard
- Barn painting py · c++ · java medium
- OA: Directory encryption with the fewest operations 2 levels Databricks medium
- Best root for a one-way tree Uber py · c++ · java medium
- Count subordinates in a company tree py · c++ · java easy
- Tree Diameter py · c++ · java easy