Tree Traversal
Visit every node in a tree — recursively (DFS) or level-by-level (BFS).
What is this pattern?
Tree problems almost always reduce to one traversal strategy. DFS (preorder, inorder, postorder) uses the call stack and is natural for computing path properties, constructing trees, or comparing structure. BFS (level-order) uses a queue and is right for level-aware problems.
When to use it
- DFS: depth, path sum, subtree comparison, LCA
- BFS: level order, minimum depth, right side view
- Inorder on BST gives sorted sequence
- Postorder when you need subtree results before parent
Key Insight
For most DFS tree problems, define a recursive function that returns something meaningful (height, count, bool) and propagates results bottom-up. Trust the recursion — you only need to handle the current node and its two children.
Pro Content
The Java template and practice problems for this pattern are part of the Pro plan. Upgrade to unlock all patterns, 500+ problems, and Aria code reviews.
From ₹3,999 for a year · one-time, no auto-renewal