Tree
Traversals, BSTs, construction, path problems and tree DP with clean recursive contracts.
DSAIntermediate24 hrs8 patterns · 40 problems
0%
your progressCore idea
Define the recursive contract: what a call returns, and what global answer it may update. Post-order for bottom-up aggregates, pre-order to pass context down, BFS for levels.
Reach for it when
- Hierarchical data, BSTs, paths between nodes
- Level-by-level questions (BFS)
- Aggregates over subtrees (height, diameter, sums)
Template
def diameter(root):
best = 0
def height(node):
nonlocal best
if not node:
return 0
l, r = height(node.left), height(node.right)
best = max(best, l + r)
return 1 + max(l, r)
height(root)
return bestComplexity
O(n) time, O(h) recursion stack (O(n) worst case for skewed trees).
Common pitfalls
- Confusing the returned value with the global answer
- BST validation using only parent comparison (needs bounds)
- Deep recursion limits on skewed inputs
Patterns in this course
Recognition cues
DFSBFSBSTConstructionTree DPPath/Distance