Binary tree traversal - breadth-first and depth-first strategies
Channel: mycodeschool
Watch on YouTube →Algorithm • medium
Tree traversal means visiting every node in a deliberate order such as preorder, inorder, postorder, or level-order.
Different orders serve different tasks: expression evaluation, sorted output, serialization, and breadth metrics.
Mastering traversal unlocks many tree-based algorithm questions quickly.
Typical Complexity Baseline
| Metric | Value |
|---|---|
| Visit all nodes | O(n) |
See It
A small animated SVG that illustrates the core idea the moving parts you need to keep in your head when you read the rest of the guide.
Each node is visited once. The order (pre/in/post) decides when the parent is read.
Watch First
A quick visual walkthrough before the detailed sections pick the format that helps you learn fastest.
Channel: mycodeschool
Watch on YouTube →Mechanics
The building blocks and terminology you need before everything else clicks. Skim or deep-read.
What it is Top entry node for traversal.
Why it matters Root node is a required building block for understanding how Tree Traversal (DFS/BFS) stays correct and performant on large inputs.
What it is Descendant references explored per traversal order.
Why it matters Children is a required building block for understanding how Tree Traversal (DFS/BFS) stays correct and performant on large inputs.
What it is Sequence rule defining visitation order.
Why it matters Traversal order is a required building block for understanding how Tree Traversal (DFS/BFS) stays correct and performant on large inputs.
What it is Tracking to prevent reprocessing in generalized graphs.
Why it matters Visited state is a required building block for understanding how Tree Traversal (DFS/BFS) stays correct and performant on large inputs.
What it is Call stack/explicit stack/queue depending on traversal type.
Why it matters Work structure is a required building block for understanding how Tree Traversal (DFS/BFS) stays correct and performant on large inputs.
What it is Visit node before children.
Why it matters Visit node before children. In Tree Traversal (DFS/BFS), this definition helps you reason about correctness and complexity when inputs scale.
What it is Visit left node, root, then right (BST yields sorted order).
Why it matters Visit left node, root, then right (BST yields sorted order). In Tree Traversal (DFS/BFS), this definition helps you reason about correctness and complexity when inputs scale.
What it is Visit children before node.
Why it matters Visit children before node. In Tree Traversal (DFS/BFS), this definition helps you reason about correctness and complexity when inputs scale.
What it is Visit by depth using queue (BFS).
Why it matters Visit by depth using queue (BFS). In Tree Traversal (DFS/BFS), this definition helps you reason about correctness and complexity when inputs scale.
What it is Longest downward path length from node.
Why it matters Longest downward path length from node. In Tree Traversal (DFS/BFS), this definition helps you reason about correctness and complexity when inputs scale.
Walkthrough
Every frame of the concept diagram, laid out top-to-bottom so you can scroll through the algorithm at your own pace.
Preorder DFS starts at root A: visit, then recurse left, then right.
Visit B. Output so far: [A, B].
Visit D. Output so far: [A, B, D].
Visit H. Output so far: [A, B, D, H].
Visit I. Output so far: [A, B, D, H, I].
Visit E. Output so far: [A, B, D, H, I, E].
Visit J. Output so far: [A, B, D, H, I, E, J].
Visit K. Output so far: [A, B, D, H, I, E, J, K].
Visit C. Output so far: [A, B, D, H, I, E, J, K, C].
Visit F. Output so far: [A, B, D, H, I, E, J, K, C, F].
Visit L. Output so far: [A, B, D, H, I, E, J, K, C, F, L].
Visit M. Output so far: [A, B, D, H, I, E, J, K, C, F, L, M].
Visit G. Output so far: [A, B, D, H, I, E, J, K, C, F, L, M, G].
Visit N. Output so far: [A, B, D, H, I, E, J, K, C, F, L, M, G, N].
Visit O. Output so far: [A, B, D, H, I, E, J, K, C, F, L, M, G, N, O].
Tradeoffs
When this technique wins, when it loses, and what to reach for instead.
Choose this when Choose tree traversal when structure is acyclic and rooted.
Tradeoff Graph traversal requires explicit visited handling for cycles.
Choose this when Choose tree traversal for hierarchical relationships.
Tradeoff Array scan is simpler for flat data.
Choose this when Choose tree traversal for strict parent-child trees.
Tradeoff Topological sort handles general DAG dependency graphs.
In Production
Where this shows up at real companies and what the on-call engineer learned the hard way.
DOM and render trees are traversed repeatedly for layout and paint phases.
Takeaway Efficient traversal directly impacts UI responsiveness.
Query planner and index structures rely on tree walks to resolve key ranges.
Takeaway Traversal strategy influences database query latency.
Scene graph processing traverses hierarchical object trees each frame.
Takeaway Predictable traversal ordering is critical for real-time systems.
Code
A clean reference implementation in TypeScript, Python, and Go. Switch languages with the toggle.
Use explicit stack to simulate recursive inorder walk.
Complexity: Time O(n), Space O(h)
Iterative inorder traversal
type TreeNode = { value: number; left: TreeNode | null; right: TreeNode | null }
function inorderValues(rootNode: TreeNode | null): number[] {
const stack: TreeNode[] = []
const values: number[] = []
let currentNode = rootNode
while (currentNode || stack.length > 0) {
while (currentNode) {
stack.push(currentNode)
currentNode = currentNode.left
}
const node = stack.pop()!
values.push(node.value)
currentNode = node.right
}
return values
}
Watch Out
The bugs and edge cases that bite engineers most often. Skim before you ship.
Pro Tips
Small habits that pay off every time you reach for this pattern.
Pattern Recognition
Concrete signals that tell you this is the right pattern both at work and on LeetCode.
Practice
A curated easy-to-hard problem ladder. Each one reinforces a specific aspect of the pattern.
| # | Problem | Difficulty | Typical Complexity |
|---|---|---|---|
| 1 | Maximum Depth of Binary Tree | Easy | O(n) |
| 2 | Invert Binary Tree | Easy | O(n) |
| 3 | Binary Tree Inorder Traversal | Easy | O(n) |
| 4 | Binary Tree Level Order Traversal | Medium | O(n) |
| 5 | Validate Binary Search Tree | Medium | O(n) |
| 6 | Lowest Common Ancestor of a Binary Tree | Medium | O(n) |
| 7 | Binary Tree Right Side View | Medium | O(n) |
| 8 | Serialize and Deserialize Binary Tree | Hard | O(n) |
| 9 | Binary Tree Maximum Path Sum | Hard | O(n) |
| 10 | Recover Binary Search Tree | Hard | O(n) |