If you have ever wondered how a search engine indexes web pages, how file systems organize directories, or how compilers parse code, the answer often involves trees. And at the heart of working with trees is traversal, the systematic way of visiting every node exactly once.
Binary tree traversal is one of those fundamental concepts that separates developers who truly understand data structures from those who just memorize code. It is the foundation for solving countless interview problems, from validating binary search trees to serializing trees to computing expression values. Once you master traversal, you unlock a whole category of problems that become straightforward.
What makes traversal interesting is the choice of order. Unlike arrays where "visiting all elements" has an obvious meaning, trees have multiple natural orderings. Each ordering serves different purposes and reveals different properties of the data. Understanding when to use which traversal is just as important as knowing how to implement them.
A binary tree is a hierarchical data structure where each node has at most two children, called the left child and right child. Traversal means visiting every node in the tree exactly once, in some specific order.
This tree has 7 nodes. Traversal answers the question: in what order should we visit them?
The three fundamental traversals for binary trees are:
| Traversal | Order | Mnemonic |
|---|---|---|
| Preorder | Root → Left → Right | Root first |
| Inorder | Left → Root → Right | Root in middle |
| Postorder | Left → Right → Root | Root last |
The names describe when we process the root relative to its subtrees. "Pre" means before (root first), "in" means in between, and "post" means after (root last).
Tree traversal is not just an academic exercise. It is the building block for solving real problems:
1. Expression Trees
Compilers represent mathematical expressions as trees. Different traversals produce different notations:
(2 + 3) (human-readable infix)+ 2 3 (prefix notation, used in Lisp)2 3 + (postfix notation, used in calculators)2. Binary Search Trees
Inorder traversal of a BST visits nodes in sorted order. This is the key insight behind many BST operations.
3. Tree Serialization
To save a tree to a file or send it over a network, you need to convert it to a sequence. Preorder traversal with null markers is a common approach.
4. DOM Manipulation
Web browsers represent HTML as a tree. Traversing this tree lets you find elements, update content, and compute layouts.
5. File System Operations
Directories form a tree. Listing all files, computing folder sizes, and deleting directories all require traversal.
Different traversals are suited to different tasks. Here is a guide:
| Problem Type | Best Traversal | Why |
|---|---|---|
| Process parent before children | Preorder | Root is visited first |
| Get sorted order from BST | Inorder | Left → Root → Right gives ascending order |
| Delete a tree | Postorder | Children must be deleted before parent |
| Clone/copy a tree | Preorder | Need to create parent before attaching children |
| Evaluate expression tree | Postorder | Need operands before applying operator |
| Validate BST | Inorder | Check if nodes appear in sorted order |
| Find path from root to node | Preorder | Build path as you descend |
| Calculate tree height/size | Postorder | Need subtree info before computing for current node |
Let us examine each traversal in detail using this example tree:
In preorder traversal, we visit the root node first, then recursively traverse the left subtree, then the right subtree.
Algorithm:
Why "preorder"? The root is processed before (pre-) its subtrees.
Result for our tree: A → B → D → E → C → F → G
Detailed trace:
Use cases:
In inorder traversal, we first recursively traverse the left subtree, then visit the root, then traverse the right subtree.
Algorithm:
Why "inorder"? The root is processed in between its subtrees.
Result for our tree: D → B → E → A → F → C → G
Detailed trace:
Special property for BST:
If the tree is a Binary Search Tree, inorder traversal visits nodes in ascending order. This is because in a BST, all left descendants are smaller than the node, and all right descendants are larger.
Inorder traversal: 1 → 3 → 6 → 8 → 10 → 14 (sorted!)
Use cases:
In postorder traversal, we first recursively traverse the left subtree, then the right subtree, then visit the root.
Algorithm:
Why "postorder"? The root is processed after (post-) its subtrees.
Result for our tree: D → E → B → F → G → C → A
Detailed trace:
Use cases:
Let us walk through a concrete example that shows why different traversals matter. Consider this expression tree representing (3 + 5) * 2:
Preorder (Prefix notation): * + 3 5 2
This is how Lisp represents expressions: (* (+ 3 5) 2)
Inorder (Infix notation): 3 + 5 * 2
This is closest to how humans write expressions, but notice it loses the parentheses! The actual expression is (3 + 5) * 2, but inorder gives 3 + 5 * 2 which would be evaluated as 3 + (5 * 2) = 13 by normal precedence rules.
Postorder (Postfix notation): 3 5 + 2 *
This is also called Reverse Polish Notation (RPN), used by HP calculators. It can be evaluated with a simple stack: push numbers, and when you see an operator, pop two numbers, apply the operator, and push the result.
This example shows why postorder is natural for evaluation: you always have the operands ready before you need to apply the operator.
Another practical example is computing the height of a tree. The height of a node is 1 + the maximum height of its children. This naturally requires postorder traversal because you need children's heights before computing the parent's height.
Trace:
Each traversal can be implemented recursively (using the call stack) or iteratively (using an explicit stack). The recursive approach is more intuitive, while the iterative approach gives you more control and avoids stack overflow for very deep trees.
The recursive implementations are elegant and directly mirror the algorithm definitions:
Time Complexity: O(n) - visit each node once
Space Complexity: O(h) where h is height of tree - for the recursion stack. In worst case (skewed tree), h = n. For balanced tree, h = log n.
Iterative implementations use an explicit stack to simulate the recursion. They are more complex but worth understanding:
We will cover the iterative implementations in detail in the subsequent chapters.
Here is a summary of all three traversals on the same tree:
| Traversal | Order | Result |
|---|---|---|
| Preorder | Root → Left → Right | 1 → 2 → 4 → 5 → 3 → 6 → 7 |
| Inorder | Left → Root → Right | 4 → 2 → 5 → 1 → 6 → 3 → 7 |
| Postorder | Left → Right → Root | 4 → 5 → 2 → 6 → 7 → 3 → 1 |
Observations:
It is easy to mix up when to visit the root. Use the mnemonic:
Always check for null nodes. The base case if (node == null) return; prevents null pointer exceptions and properly handles empty subtrees.
If you modify the tree structure while traversing (like removing nodes), you may skip nodes or visit them multiple times. Either collect nodes to modify in a list and process after traversal, or use careful iteration with proper bookkeeping.
Choosing the wrong traversal makes problems harder than they need to be:
Q1: Explain the difference between preorder, inorder, and postorder traversal.
The difference lies in when the root node is processed relative to its subtrees. In preorder traversal (Root → Left → Right), we process the root first, then recursively traverse the left subtree, then the right subtree. This is useful when you need to create a copy of the tree or print the structure from top down. In inorder traversal (Left → Root → Right), we first traverse the left subtree, then process the root, then traverse the right subtree. For a binary search tree, this visits nodes in sorted ascending order. In postorder traversal (Left → Right → Root), we traverse both subtrees first before processing the root. This is essential when computation at a node depends on results from its children, like calculating tree height or deleting a tree safely.
Q2: Why does inorder traversal of a BST give sorted order?
In a binary search tree, every node follows the BST property: all nodes in the left subtree have values less than the node, and all nodes in the right subtree have values greater than the node. Inorder traversal visits the left subtree first, which contains all smaller values. Then it visits the current node. Then it visits the right subtree, which contains all larger values. By recursively applying this to each subtree, we visit nodes in ascending order. At any node, we have already visited all smaller values in its left subtree, we then visit this node, and we will next visit all larger values in its right subtree. This property makes inorder traversal extremely useful for BST operations like finding the kth smallest element or checking if a tree is a valid BST.
Q3: When would you use iterative traversal instead of recursive?
Iterative traversal is preferred in several scenarios. First, for very deep trees, recursive traversal may cause stack overflow because each recursive call adds a frame to the call stack. Languages without tail call optimization are particularly vulnerable. Iterative traversal with an explicit stack gives you control over memory usage. Second, when you need to pause and resume traversal, iterative gives you more control. Third, some problems are easier to implement iteratively, like Morris traversal which achieves O(1) space by temporarily modifying the tree. Fourth, in production code handling potentially adversarial input, iterative implementations are more robust. That said, recursive implementations are cleaner and more intuitive for most interview scenarios, and interviewers generally accept them unless the problem specifically requires iterative approach or the tree might be extremely deep.
Q4: How can you reconstruct a binary tree from its traversals?
You can uniquely reconstruct a binary tree if you have inorder traversal plus either preorder or postorder traversal. With preorder and inorder: the first element of preorder is the root. Find this element in inorder, everything to its left in inorder is the left subtree, everything to its right is the right subtree. Recursively apply this using the corresponding segments of preorder. With postorder and inorder: similar approach, but the last element of postorder is the root. However, you cannot reconstruct a unique tree from just preorder and postorder. The reason is that preorder and postorder can identify subtree boundaries but not distinguish between left-only and right-only children. Inorder is essential because it explicitly separates left and right subtrees. This is a common interview problem and understanding why each traversal contributes information is key.
Binary tree traversal is the foundation of tree manipulation. The three fundamental traversals, preorder, inorder, and postorder, differ only in when the root is processed relative to its subtrees.
Key takeaways:
In the next chapter, we will implement Binary Tree Preorder Traversal with both recursive and iterative approaches, diving deep into the mechanics of each.