Binary Trees & Traversals
Preorder, inorder, postorder and level order, and thinking recursively about trees.
Ask a binary tree for its longest path and the naive answer tries every pair of nodes. Ask each subtree instead for one number, its height, and the answer falls out of a single pass that visits every node once. This lesson builds that habit: the four traversal orders, how to run them with or without recursion, how to rebuild a tree from two of them, and how to decide what each subtree should report to its parent.
What you’ll learn
- Define binary trees recursively, prove the counting facts ( edges, empty pointers, ), and store a tree with pointers or, when it is complete, in an array.
- Implement preorder, inorder, postorder and level order recursively and iteratively, in time with or extra space.
- Rebuild a binary tree from its preorder and inorder in , and explain why preorder and postorder do not determine it.
- Solve height, diameter, balance and path problems with one postorder pass in which each subtree reports what its parent needs.
- Recognize tree problems, choose the traversal order by data flow, and avoid stack overflows on degenerate trees.
Binary trees, recursively
A binary tree is defined recursively: it is either empty, or a node holding a key together with two binary trees, its left and right subtrees. Algorithms follow the same shape: handle the empty tree, then combine a node with the answers for its two subtrees. Proofs follow it too, by structural induction: prove a statement for the empty tree, then for a node assuming it holds for both subtrees.
A few counting facts are used constantly. Write for the number of nodes and for the height, the number of edges on the longest root-to-leaf path, with for the empty tree.
Edges and empty pointers. Every node except the root has exactly one parent, so exactly of the child pointers lead to a node, and those are the edges. The rest are empty:
Height. Depth holds at most nodes, since each node has at most two children. Summing over the depths , and using that is an integer:
Full trees. Count the edges twice: each of the internal nodes has two children, and every node but the root has one parent. With leaves:
Representations. The usual one is linked: each node stores its key and two pointers, sometimes a parent pointer too. A complete tree needs no pointers at all: store it level by level in an array, and the children of index sit at and , its parent at . That is how a binary heap lives; segment trees often use the 1-indexed variant, with children and . For other shapes the array layout wastes space: a path of height would occupy cells.
A rooted tree with any number of children per node becomes a binary tree under the left-child, right-sibling representation: the left pointer leads to the first child, the right pointer to the next sibling. Much of this lesson therefore applies to general trees as well.
Think first A binary tree has 1,000 nodes. How short can it be, and how tall?
At least , since height 8 leaves room for only nodes; a complete tree achieves 9. At most , when the tree is a single path. Every algorithm whose cost is , such as a BST search, lives somewhere in that range, which is why balancing matters.
Four traversals, two ways to run them
The three depth-first orders differ only in where the visit sits among the two recursive calls: before them (preorder), between them (inorder) or after them (postorder). Level order is breadth-first: it keeps a queue and visits depth 0, then depth 1, and so on.
def preorder(x, out):
if x:
out.append(x.key); preorder(x.left, out); preorder(x.right, out)
def inorder(x, out):
if x:
inorder(x.left, out); out.append(x.key); inorder(x.right, out)
def postorder(x, out):
if x:
postorder(x.left, out); postorder(x.right, out); out.append(x.key)There is one call per node and one per empty pointer, calls of work each: time. The call stack holds one frame per node on the current root path, so the extra space is : for a balanced tree, for a path.
from collections import deque
def inorder_iter(root):
out, stack, x = [], [], root
while stack or x:
while x: # push the left spine of x
stack.append(x)
x = x.left
x = stack.pop() # leftmost node not yet visited
out.append(x.key)
x = x.right # then walk its right subtree
return out
def level_order(root):
levels, q = [], deque([root] if root else [])
while q:
level = []
for _ in range(len(q)): # exactly the nodes of one depth
x = q.popleft()
level.append(x.key)
if x.left: q.append(x.left)
if x.right: q.append(x.right)
levels.append(level)
return levelsThe explicit stack holds the nodes whose left subtree is being walked and whose own visit is still due. Iterative preorder pops a node, visits it, and pushes its right child before its left; iterative postorder can run the mirror preorder (node, right, left) and reverse the output. The iterative depth-first versions were checked against the recursive ones on 3,000 random trees.
Level order runs on a perfect binary tree with nodes (height 9). What is the largest number of nodes waiting in the queue at any moment?
Show the answer
512 nodes
The queue peaks when the last node of depth 8 has been processed: all nodes of the bottom level are waiting, half the tree. A depth-first walk of the same tree never holds more than 10 nodes, one per level of the current path. Level order needs extra space, where is the widest level, and depth-first order ; on bushy trees depth-first is far leaner, unless you need the levels.
Rebuilding a tree from two traversals
One traversal does not pin down a tree: label each of the five binary trees with three nodes in preorder, and all five have preorder 1 2 3. Two traversals can, as long as one of them is the inorder.
The empty sequences give the empty tree. Otherwise the first key of the preorder is the root. Since keys are distinct, occurs once in the inorder, at some position , and inorder lists the left subtree, then , then the right subtree:
So the left subtree has exactly nodes, and the preorder lists the root, then the whole left subtree, then the whole right subtree:
Each subtree has fewer than nodes, and we now hold its preorder and its inorder, so by induction each subtree is determined, and with it the whole tree. Looking up in a hash map of inorder positions makes each step :
def build(preorder, inorder):
pos = {key: i for i, key in enumerate(inorder)} # keys must be distinct
it = iter(preorder)
def make(lo, hi): # the subtree whose inorder is inorder[lo:hi]
if lo == hi:
return None
key = next(it) # preorder lists that subtree's root first
node = Node(key)
node.left = make(lo, pos[key])
node.right = make(pos[key] + 1, hi)
return node
return make(0, len(inorder))The recursion consumes the preorder in exactly its own order (root, left subtree, right subtree), so one iterator replaces all index arithmetic. Scanning the inorder for each root instead of using pos costs in the worst case, a path. Checked by rebuilding 3,000 random trees from their traversals.
Inorder plus postorder works the same way (the root is last in postorder), and so does inorder plus level order. Without the inorder, information is lost. Preorder 1 2 with postorder 2 1 fits two trees: 2 can be the left or the right child of 1.
In general, preorder and postorder together fix every parent–child relation and the order of siblings, but not which side a lone child hangs on. If nodes have exactly one child, binary trees share both sequences, so for full binary trees () the pair does determine the tree.
A binary tree with distinct keys has preorder 4 2 1 3 6 5 7 and inorder 1 2 3 4 5 6 7. What is its postorder?
- 1 2 3 5 6 7 4
- 7 5 6 3 1 2 4
- 1 3 2 5 7 6 4
- 2 1 3 6 5 7 4
Show the answer
C. 1 3 2 5 7 6 4
The root is 4, first in the preorder. In the inorder, 1 2 3 lie to its left and 5 6 7 to its right. The left subtree's preorder is 2 1 3, so its root is 2 with children 1 and 3; likewise the right subtree is 6 with children 5 and 7. Postorder lists each subtree before its root: 1 3 2, then 5 7 6, then 4.
Thinking recursively: what should a subtree report?
Most binary-tree problems are solved by one postorder pass: get the answers for the two subtrees, then combine them at the node. The design question is what each subtree must report to its parent. Size and height need one number each: , and with . The diameter shows the pattern at its best.
Every path has a top. A path in a tree climbs to its highest node and then descends; it cannot descend and climb again, since that would revisit a node. Below it enters at most two of 's child subtrees, one on each side.
The best path with top . Each side contributes one edge into the child plus at most that child's height, and an absent side contributes nothing, which the convention handles automatically. Descending to a deepest node on each side attains the bound:
Maximize over the top. Every path has exactly one top, so the diameter is the best value over all nodes, and the heights it needs are exactly what the postorder pass computes anyway:
Cost. The pass does work per node: . Calling a fresh height function at every node instead costs the sum of all subtree sizes, every node counted once per ancestor:
def diameter_and_balance(root):
best, balanced = 0, True
def height(x): # postorder: both children first
nonlocal best, balanced
if x is None:
return -1
hl, hr = height(x.left), height(x.right)
best = max(best, hl + hr + 2) # longest path whose top node is x
if abs(hl - hr) > 1:
balanced = False # x breaks the height-balance rule
return 1 + max(hl, hr) # what the parent needs
height(root)
return best, balancedThe function returns what the parent needs, the height, and records what the problem asks for on the side. Checked against a breadth-first search from every node on 3,000 random trees.
The same habit solves a whole family of problems in :
- Maximum path sum, keys possibly negative: return the best downward path from the node, with each child's contribution clamped at 0, and record as a candidate.
- A root-to-leaf path with sum : preorder, passing the remaining sum down to the children.
- Symmetric tree: compare the left subtree with the mirror image of the right one, recursing on the pairs (left.left, right.right) and (left.right, right.left).
- Lowest common ancestor of and . In a BST, walk down from the root until the two keys split: the first node with is the answer, in . In a general tree, a postorder pass reports whether each subtree contains or ; the lowest node that has one of them on each side, or is one of them with the other below it, is the answer: per query.
Think first For the maximum path sum, why must the recursion return the best downward path from a node rather than the best path anywhere in its subtree?
Only a downward path can be extended through the parent: a path that already bends at a node uses both of that node's sides and cannot continue upward. So each call returns the best path starting at its node, which is what the parent can use, and records the best bending path on the side. When a node needs several such numbers from each child, the pass returns a tuple per subtree, and that is dynamic programming on trees.
Recognizing it
Reach for a tree traversal when:
- the input is a tree or a hierarchy: nodes with child pointers, a parent array, nested folders, an org chart, an arithmetic expression, a thread of replies;
- the question concerns every subtree ("for each node, …"), root-to-leaf paths, or levels ("by depth", "nearest to the root", "seen from the side");
- goes up to about or , so the intended solution is a single pass.
Then pick the order by data flow: postorder when a node needs its children's answers, preorder when children need something from their ancestors (a depth, a running sum, the path so far), inorder when a BST's sorted order matters, level order when depth or distance from the root does.
| Problem (in brief) | Key idea | Cost |
|---|---|---|
| Longest path between any two nodes | Return the height; record at every node | |
| Largest sum along any path, keys may be negative | Return the best downward path, children clamped at 0; record key plus both gains | |
| The node seen at each depth from the right side | Level order; keep the last node of each level | |
| Rebuild a tree from its preorder and inorder | Root first in preorder; split the inorder at it; hash map of positions | |
| Turn a tree into a string and back | Preorder with a marker per empty pointer: tokens |
You need the depth of the shallowest leaf in a huge, lopsided tree, touching as few nodes as possible. Which traversal fits?
- Postorder, combining the children's minimum depths
- Level order, stopping at the first leaf it dequeues
- Inorder, since it reaches the leftmost leaf first
- Preorder, reporting the depth of the first leaf it reaches
Show the answer
B. Level order, stopping at the first leaf it dequeues
Level order dequeues nodes in order of depth, so the first leaf it dequeues is a shallowest one, and it stops before dequeuing anything deeper. A depth-first order may dive down a long branch first and must finish every branch before it can be sure.
Key takeaways
- A binary tree is empty or a node with two binary subtrees. With nodes it has edges and empty pointers, and its height is at least .
- Preorder, inorder and postorder differ only in when a node is visited. Recursively or with an explicit stack they take time and extra space; level order uses a queue and space.
- Inorder together with preorder, postorder or level order determines a tree with distinct keys, rebuilt in with a hash map of positions; preorder with postorder leaves trees when nodes have one child.
- Most tree problems are one postorder pass in which each subtree returns what its parent needs (a height, a best downward path) while the answer is recorded on the side: diameter, balance and maximum path sum all take .
- Recursion depth equals the height: when a tree can degenerate into a path, use an explicit stack or raise the limits.
Check yourself
In the interactive lesson these are scored with your confidence, and what you miss comes back for review.
A binary tree has nodes. It is serialized in preorder, writing each key and a marker for every empty child pointer. How many tokens are written?
Show the answer
C.
keys plus markers: of the child pointers, lead to nodes and are empty. The markers make the preorder alone sufficient, because they say exactly where each subtree ends; reading the tokens back with the same recursion rebuilds the tree.
Which pair of traversals does not always determine a binary tree with distinct keys?
- Preorder and postorder
- Preorder and inorder
- Postorder and inorder
- Level order and inorder
Show the answer
A. Preorder and postorder
Without the inorder, a node with a single child does not reveal which side the child hangs on: preorder 1 2 and postorder 2 1 fit both trees in which 2 is a child of 1. With single-child nodes, trees share both sequences; for full binary trees the pair does suffice.
A diameter routine calls a fresh height function at every node. On a path of nodes, how does it compare with the one-pass version?
- against
- Both are , since every node is visited
- against
- against
Show the answer
C. against
A fresh height call at node visits all of 's subtree, so the total is the sum of all subtree sizes: on a path. The one-pass version returns each height to the parent and does work per node.
The iterative inorder traversal (push the left spine, pop, visit, go right) runs on a BST built by inserting in increasing order. What is the largest size its stack reaches?
- , the height plus one
- About
- About
Show the answer
B.
The tree is a path of right children. No node has a left spine, so the loop pushes one node, pops it, visits it and moves right: the stack never holds more than one node. Recursive inorder on the same tree is calls deep, because each call waits for its right subtree; the iterative version turns that last call into a loop. Inserting in decreasing order builds a left path, and then the stack does reach .
In the BST built by inserting 8, 3, 10, 1, 6, 14, 4, 7, 13, what is the lowest common ancestor of 4 and 7?
- 8, the root
- 3
- 4
- 6
Show the answer
D. 6
Walk down from the root: 4 and 7 are both smaller than 8, so go left to 3; both are larger than 3, so go right to 6; and , so the paths to 4 and 7 split here. 4 and 7 are the two children of 6.
Go deeper
- Lowest Common Ancestors · Binary lifting, Euler tours with range minimum, and Tarjan’s offline algorithm.
- Heavy-Light & Centroid Decomposition · Breaking trees into paths and parts for fast path queries.
- Tree Traversal in O(1) Space · Threaded trees, Morris traversal and pointer reversal.
Further reading
- D. E. Knuth, The Art of Computer Programming, vol. 1: Fundamental Algorithms, 3rd ed. (Addison-Wesley, 1997), section 2.3.
- T. H. Cormen, C. E. Leiserson, R. L. Rivest & C. Stein, Introduction to Algorithms, 4th ed. (MIT Press, 2022), chapter 10 (representing rooted trees) and section 12.1.
- A. Laaksonen, Competitive Programmer's Handbook (2018, free online), chapter 14.