Trees (DFS & BFS)
Signal: the input is a TreeNode root; depth, paths, ancestors, ordering in a BST, level-by-level output, comparing subtrees.
Core idea: almost every tree problem is a traversal plus the right information flowing up or down:
- Bottom-up (post-order): each call returns something about its subtree (height, sum, "is valid"), and the parent combines its children's answers. Most "max/min/diameter/balanced" problems.
- Top-down (pre-order): pass state down (current path sum, allowed value range).
- Level-order (BFS): a queue processes nodes level by level, for "per level", "minimum depth" and "right side view" questions.
Templates
python
# Bottom-up DFS: return info about the subtree
def height(node):
if not node:
return 0
return 1 + max(height(node.left), height(node.right))
# Top-down DFS: pass constraints down
def valid(node, lo, hi):
if not node: return True
if not (lo < node.val < hi): return False
return valid(node.left, lo, node.val) and valid(node.right, node.val, hi)
# BFS level order
from collections import deque
q = deque([root])
while q:
for _ in range(len(q)): # exactly one level
node = q.popleft()
...
if node.left: q.append(node.left)
if node.right: q.append(node.right)The "global answer" trick
When the answer isn't what the recursion naturally returns (e.g., diameter, max path sum), return one thing (the best downward path) and update a separate global/nonlocal best with another (the path through this node).
Trees in the tests use LeetCode's level-order array format, e.g. [8, 3, 10, 1, 6, null, 14], which is converted to TreeNodes for you.