Tree Traversals
A traversal visits every node of a tree exactly once, in a fixed order. Preorder, inorder and postorder go deep first and differ only in when a node is written; level order goes row by row with a queue.
What Tree Traversal Means
- Preorder: node, then left subtree, then right subtree
- Inorder: left subtree, then node, then right subtree
- Postorder: left subtree, then right subtree, then node
Tree traversal in data structure means visiting every node of a tree exactly once in a set order, for example to print it, copy it or add up its values. An array or a linked list has one natural order. A tree branches, so you have to choose one.
There are two families. Depth-first orders go all the way down one branch before trying the next: preorder, inorder and postorder. Level order finishes each depth before going deeper.
The three depth-first orders are the same recursion. Each call does three things: handle the node, recurse left, recurse right. Only the position of "handle the node" changes, and the name says where it goes. Left always comes before right.
- Each order is O(n) time: every node is handled once
- Recursion uses O(h) stack space, where h is the tree's height
Inorder, Preorder and Postorder: What Each Is For
Each order exists because some job needs exactly that sequence.
Preorder traversal handles a parent before its children, so it suits jobs that work top-down. Copying a tree must create a node before it can attach children to it. Saving a tree to a file writes the parent first so a reader can rebuild it from the top. A printed folder tree lists each folder before what is inside it.
Postorder traversal handles the children before the parent, so it suits jobs where the parent needs its children's answers. Freeing a tree must delete children first, or the pointers to them are lost. A height or size needs both subtree values before combining them. An expression tree must evaluate both operands before applying the operator.
Inorder traversal only makes sense on a binary tree, since it sits between two sides. On a binary search tree it lists the keys in ascending order, because everything on the left is smaller and everything on the right is larger. That is how you validate a BST (each key must beat the one before) or find the kth smallest key (count k visits). On a tree that is not a search tree, inorder has no special meaning.
| Order | Sequence | Use it for |
|---|---|---|
| Preorder | Node, left, right | Copying, saving to a file, top-down work |
| Inorder | Left, node, right | Sorted keys from a BST, BST checks, kth smallest |
| Postorder | Left, right, node | Freeing, heights and sizes, evaluating expressions |
| Level order | Depth by depth, with a queue | Per-level output, minimum depth, right-side view |
- Preorder builds top-down; postorder combines bottom-up
- Inorder gives sorted output only on a search tree
Level Order with a Queue
- Put the root in the queue
- Note the queue size k at the start of the round
- Take out k nodes, visit each, and add its children to the back
- Repeat until the queue is empty
Level order visits the root, then every node at depth 1, then every node at depth 2, and so on. It is breadth-first search run on a tree. A stack would dive down one branch, so level order uses a queue instead: first in, first out keeps each level ahead of the next.
To get the levels as separate lists, record the queue's size at the start of each round and take out exactly that many nodes. Those are the whole current level, because all of them went in before any of their children.
Memory works the other way round from the depth-first orders. Level order holds up to one full level, O(w) for width w; a full tree's last level has about n/2 nodes. Depth-first holds one path, O(h). So a wide, shallow tree favours depth-first, and a deep, thin tree favours level order.
- Answers per-level questions such as the right-side view
- The first leaf it reaches is at the minimum depth
Terms, operations, and practical uses
Depth-first orders
- PreorderVisit the node, then its left subtree, then its right subtree. The root always comes first.
- InorderVisit the left subtree, then the node, then the right subtree. Sorted order on a binary search tree.
- PostorderVisit both subtrees, then the node. The root always comes last, so children are done before their parent.
Level order
- QueueHolds nodes waiting to be visited. First in, first out keeps every node of one depth ahead of the next depth.
- Level sizeThe queue's length at the start of a round. Taking exactly that many nodes groups the output by level.
- WidthThe most nodes on any one level. Level order needs memory for that many nodes.
Doing it without recursion
- Explicit stackReplaces the call stack so a very deep tree cannot overflow it. Preorder pushes the right child before the left.
- Morris traversalInorder in O(1) extra space: temporary links from each left subtree's rightmost node back up to the current node.
- ReconstructionInorder plus preorder (or postorder) rebuilds a binary tree with distinct keys; preorder plus postorder does not.
Code in Python, C++ and Java
from collections import deque
class Node:
def __init__(self, val, left=None, right=None):
self.val, self.left, self.right = val, left, right
def preorder(node, out):
if node:
out.append(node.val)
preorder(node.left, out)
preorder(node.right, out)
return out
def inorder(node, out):
if node:
inorder(node.left, out)
out.append(node.val)
inorder(node.right, out)
return out
def postorder(node, out):
if node:
postorder(node.left, out)
postorder(node.right, out)
out.append(node.val)
return out
def level_order(root):
levels, queue = [], deque([root] if root else [])
while queue:
level = []
for _ in range(len(queue)): # exactly the nodes of this level
node = queue.popleft()
level.append(node.val)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
levels.append(level)
return levels
root = Node(8, Node(4, Node(2), Node(6)), Node(10, None, Node(12)))
show = lambda xs: " ".join(map(str, xs))
print("preorder:", show(preorder(root, [])))
print("inorder:", show(inorder(root, [])))
print("postorder:", show(postorder(root, [])))
print("level order:", " | ".join(show(l) for l in level_order(root)))#include <iostream>
#include <queue>
#include <string>
#include <vector>
using namespace std;
struct Node {
int val;
Node *left, *right;
Node(int v, Node* l = nullptr, Node* r = nullptr) : val(v), left(l), right(r) {}
};
void preorder(Node* node, vector<int>& out) {
if (!node) return;
out.push_back(node->val);
preorder(node->left, out);
preorder(node->right, out);
}
void inorder(Node* node, vector<int>& out) {
if (!node) return;
inorder(node->left, out);
out.push_back(node->val);
inorder(node->right, out);
}
void postorder(Node* node, vector<int>& out) {
if (!node) return;
postorder(node->left, out);
postorder(node->right, out);
out.push_back(node->val);
}
vector<vector<int>> levelOrder(Node* root) {
vector<vector<int>> levels;
queue<Node*> q;
if (root) q.push(root);
while (!q.empty()) {
vector<int> level;
for (int k = q.size(); k > 0; k--) { // exactly the nodes of this level
Node* node = q.front();
q.pop();
level.push_back(node->val);
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
levels.push_back(level);
}
return levels;
}
string show(const vector<int>& xs) {
string s;
for (size_t i = 0; i < xs.size(); i++) s += (i ? " " : "") + to_string(xs[i]);
return s;
}
int main() {
Node* root = new Node(8, new Node(4, new Node(2), new Node(6)), new Node(10, nullptr, new Node(12)));
vector<int> pre, in, post;
preorder(root, pre);
inorder(root, in);
postorder(root, post);
cout << "preorder: " << show(pre) << "\n";
cout << "inorder: " << show(in) << "\n";
cout << "postorder: " << show(post) << "\n";
vector<vector<int>> levels = levelOrder(root);
cout << "level order: ";
for (size_t i = 0; i < levels.size(); i++) cout << (i ? " | " : "") << show(levels[i]);
cout << "\n";
}import java.util.*;
public class Main {
static class Node {
int val;
Node left, right;
Node(int v, Node l, Node r) { val = v; left = l; right = r; }
Node(int v) { this(v, null, null); }
}
static void preorder(Node node, List<Integer> out) {
if (node == null) return;
out.add(node.val);
preorder(node.left, out);
preorder(node.right, out);
}
static void inorder(Node node, List<Integer> out) {
if (node == null) return;
inorder(node.left, out);
out.add(node.val);
inorder(node.right, out);
}
static void postorder(Node node, List<Integer> out) {
if (node == null) return;
postorder(node.left, out);
postorder(node.right, out);
out.add(node.val);
}
static List<List<Integer>> levelOrder(Node root) {
List<List<Integer>> levels = new ArrayList<>();
Deque<Node> q = new ArrayDeque<>();
if (root != null) q.add(root);
while (!q.isEmpty()) {
List<Integer> level = new ArrayList<>();
for (int k = q.size(); k > 0; k--) { // exactly the nodes of this level
Node node = q.poll();
level.add(node.val);
if (node.left != null) q.add(node.left);
if (node.right != null) q.add(node.right);
}
levels.add(level);
}
return levels;
}
static String show(List<Integer> xs) {
StringJoiner j = new StringJoiner(" ");
for (int x : xs) j.add(String.valueOf(x));
return j.toString();
}
public static void main(String[] args) {
Node root = new Node(8, new Node(4, new Node(2), new Node(6)), new Node(10, null, new Node(12)));
List<Integer> pre = new ArrayList<>(), in = new ArrayList<>(), post = new ArrayList<>();
preorder(root, pre);
inorder(root, in);
postorder(root, post);
System.out.println("preorder: " + show(pre));
System.out.println("inorder: " + show(in));
System.out.println("postorder: " + show(post));
StringJoiner lv = new StringJoiner(" | ");
for (List<Integer> l : levelOrder(root)) lv.add(show(l));
System.out.println("level order: " + lv);
}
}Step through it
Running on search tree 8 (4 (2, 6), 10 (-, 12)), then two 2-node trees and a 5-node chain
Iterative Traversal and Morris Traversal
Recursion keeps one call open per level. On a balanced tree that is about log2 n calls, but a tree built from sorted keys is a chain, and a million-node chain overflows the call stack. The iterative versions keep their own stack instead.
Preorder is the easy one: push the root; pop a node, visit it, then push its right child before its left so the left comes off first. Pushing in the wrong order gives node, right, left.
Inorder cannot visit a node until its left side is done. Walk left, pushing every node; when you reach null, pop, visit, and step to the popped node's right child. The stack holds the ancestors still waiting for their visit.
Postorder is the awkward one, since a popped node may still have an unvisited right side. The simplest fix is to run node, right, left (preorder with the pushes swapped) and reverse the result, which gives left, right, node.
Morris traversal does inorder with O(1) extra space and no stack. Before going left, it links the rightmost node of the left subtree back to the current node, uses that link to climb back, then removes it. It changes the tree while it runs, so it is not safe if another thread is reading the tree. A threaded binary tree keeps those links permanently.
- Iterative preorder: push right, then left
- Iterative postorder: reverse a node-right-left walk
- Morris: O(1) space, but it edits the tree while it runs
Rebuilding a Tree from Two Traversals
Preorder plus inorder fixes a binary tree exactly (given distinct keys). Preorder's first value is the root. Find it in inorder: everything to its left is the left subtree and everything to its right is the right subtree. Repeat on each side. Postorder plus inorder works the same way, taking the root from the end. Both are classic problems: preorder and inorder and inorder and postorder.
Preorder plus postorder is not enough. A root 8 with one child 4 gives preorder 8 4 and postorder 4 8 whether 4 is on the left or the right. Inorder is the list that supplies the split point. The exception is a full binary tree, where every node has 0 or 2 children, so a lone child never occurs.
- Inorder plus one other order rebuilds the tree
- Preorder plus postorder is ambiguous when a node has one child
Complexity and Edge Cases
All four orders visit each node once, so they take O(n) time. The difference is memory.
- Time: O(n) for preorder, inorder, postorder and level order
- Space: O(h) for recursion or an explicit stack, O(w) for level order, O(1) for Morris
- Empty tree: every order returns nothing; check for null before the first call
- One node: all four orders give that node
- A chain of n nodes: depth-first space becomes O(n)
- Duplicate keys break rebuilding, since the root's position in inorder is no longer unique