Tree Traversal: Complete Guide with Examples and Complexity
Tree traversal is where almost every tree problem starts. Validate a binary search tree, compute the height of a tree, serialize it to a string, find the maximum path sum. Every one starts from the same decision, the order in which you visit the nodes. Once the four standard traversals are automatic, most tree problems shrink to picking the right order and adding a small amount of logic on top.
Definition: tree traversal means visiting every node in a tree exactly once, in a defined order. Two families exist. Depth-first traversal, which covers inorder, preorder, and postorder, goes down one branch as far as it can before backtracking. Breadth-first traversal, which is level-order, processes the tree one level at a time.
Real-World Analogy
Think of a tree as a folder structure on your computer. Preorder is a plain directory listing. You print the current folder, then each subfolder, then each sub-subfolder. Postorder is how you calculate the total size of a folder. The parent folder cannot know its size until every subfolder has reported its own, so the folder itself is processed last. Level-order is a listing grouped by depth, everything one level down, then everything two levels down.
Inorder has no natural equivalent in a file system, because it only makes sense when the left and right children carry an ordering. That is exactly what a binary search tree gives you. In a BST, inorder visits values from smallest to largest, which is why it is the default order for validation and for producing sorted output.
Visual Explanation
Here is a sample binary tree with seven nodes.
flowchart TD
A((1)) --> B((2))
A --> C((3))
B --> D((4))
B --> E((5))
C --> F((6))
C --> G((7))
The four orders produce these sequences:
| Order | Output |
|---|---|
| Inorder (left, root, right) | 4, 2, 5, 1, 6, 3, 7 |
| Preorder (root, left, right) | 1, 2, 4, 5, 3, 6, 7 |
| Postorder (left, right, root) | 4, 5, 2, 6, 7, 3, 1 |
| Level-order (BFS) | 1, 2, 3, 4, 5, 6, 7 |
The only difference between the three depth-first orders is where the “process this node” step sits relative to the two recursive calls. In preorder it comes first, in inorder it sits between the children, and in postorder it comes last. The recursion is identical in all three. Moving one line changes the entire sequence, which is both the strength and the trap of this pattern.
Level-order is the odd one out. It uses a queue instead of a stack, and it never goes deep before returning to a shallower level. The queue holds exactly the frontier, the nodes at the current depth, with their children waiting behind them.
When to Use This Pattern
- The input is a tree, binary or n-ary, and the problem asks you to visit all nodes. Any property that must hold everywhere, like “every subtree is balanced” or “two trees are identical”, starts with a traversal.
- The tree is a BST and you need values in sorted order. Inorder produces them in a single pass.
- The answer for a node depends on the answers for its children, like height, subtree sums, or the maximum path sum. Postorder is the shape for those.
- You need to rebuild or copy a tree, through serialization, deserialization, cloning, or reconstruction from a traversal. Preorder works because the root arrives before its children.
- The problem asks for results level by level, or for the shortest path from the root. Level-order is the only order that sees depth explicitly.
Complexity Analysis
All four traversals visit each node exactly once, so the time is the same. The space depends on the data structure used.
| Traversal | Time | Space | Notes |
|---|---|---|---|
| Recursive DFS | O(N) | O(H) | Call stack holds one frame per level |
| Iterative DFS | O(N) | O(H) | Explicit stack, no recursion limit |
| BFS (level-order) | O(N) | O(W) | Queue holds one full level |
The time is
Common Mistakes
Forgetting the base case. Every recursive traversal needs the same base case. A null node returns without doing anything. Newcomers either omit it and crash on the first leaf, or they check for null in the wrong place so an empty subtree still gets processed. Before writing code, trace the two smallest inputs, an empty tree and a single node. If both work, the base case is right.
Putting the process step in the wrong order. Preorder, inorder, and postorder share one skeleton with the process line moved. Mixing them up is silent. A BST validation that compares each node against the previous one will quietly pass some invalid trees if the comparison happens at the wrong moment, and a serialized tree will not rebuild. Write the expected output for a root with one left and one right child by hand before running anything.
Forgetting to snapshot the level size in BFS. Level-order must process exactly the nodes that were in the queue when the level started. If the inner loop reads the queue length live, children pushed during the loop get absorbed into the same level and the output flattens into one list. Take the size once, before the inner loop.
Assuming recursion depth is fine. DFS recursion uses one stack frame per level. A tree that leans to one side is N levels deep, so a recursive traversal of a large skewed tree overflows the call stack even though the algorithm is correct. That is why interviewers ask for the iterative version. When the problem does not bound the height, reach for the explicit stack.
Related Patterns
- Recursion . Tree traversal is recursion applied to a tree shape. The recursive skeleton here is the same one the recursion page teaches, with the visit step moved around.
- Graph Traversal . A tree is a graph with no cycles. BFS and DFS on graphs are the same two families, with a visited set added so nodes are not revisited.
- Queue . Level-order is BFS, and BFS runs on a queue. The queue page covers the level-size snapshot trick in detail.
Next Steps
Once the orders are clear, the next step is making the code automatic. The code templates page has the recursive and iterative versions in 6 languages, and the practice problems page applies them to real interview questions from Easy to Hard.