Vocabulary
A tree is a set of nodes connected so that there is exactly one path between any two of them. One node is the root. Every other node has exactly one parent, and the nodes directly below a node are its children. A node without children is a leaf. A node together with everything below it is a subtree.
In a binary tree every node has at most two children, called left and right; the distinction matters, so a node with only a right child differs from one with only a left child.
- The depth of a node is the number of edges from the root to it. The root has depth 0.
- The height of a tree is the largest depth of any node. This lesson counts edges, so a single node has height 0. Some books count nodes instead; check the convention before comparing numbers.
The lab's sample tree, given in level order as 8 4 12 2 6 10 14 1 null 5 7, has root 8, height 3, and
leaves 1, 5, 7, 10 and 14. It also happens to be a binary search tree, which makes one of the
traversals produce something useful.
Reading the input format
The lab builds trees from a level-order list with nulls, the format many problem sites use. Read
it left to right, filling the tree one level at a time; null marks a missing child. The children of a
missing node are not listed. In the sample, null after 1 says that 2 has no right child, and the
next two values, 5 and 7, are therefore the children of 6.
Depth-first: three orders, one recursion
Every depth-first traversal does the same three things at each node: handle the left subtree, handle the right subtree, and visit the node (record it, print it, process it). Only the position of the visit changes.
preorder(node): inorder(node): postorder(node):
if node is null: return if node is null: return if node is null: return
visit(node) inorder(node.left) postorder(node.left)
preorder(node.left) visit(node) postorder(node.right)
preorder(node.right) inorder(node.right) visit(node)
On the sample tree:
| Order | Rule | Result |
|---|---|---|
| Preorder | node, left, right | 8 4 2 1 6 5 7 12 10 14 |
| Inorder | left, node, right | 1 2 4 5 6 7 8 10 12 14 |
| Postorder | left, right, node | 1 2 5 7 6 4 10 14 12 8 |
The if node is null: return line is the base case. Every leaf makes two such calls, one per
missing child, and the lab shows them as brief "empty subtree" steps.
Watch the call stack panel while stepping through. Each recursive call pushes a frame, and a frame is popped only when both of its subtrees are done. The stack always holds the path from the root to the current node, which is why depth-first traversal needs memory proportional to the height.
What each order is good for
- Preorder meets a node before anything below it. Use it to copy a tree, to serialize it so it can be rebuilt, or to print an indented outline: a directory listing that shows each folder before its contents is a preorder walk.
- Inorder on a binary search tree yields the keys in sorted order, because everything in the left subtree is smaller than the node and everything in the right subtree is larger. On a tree that is not a BST, inorder has no special meaning. Checking that an inorder walk is strictly increasing is one way to validate a BST.
- Postorder meets a node after everything below it. Use it whenever a node's answer depends on its children's answers: subtree sizes, heights, evaluating an expression tree, or freeing a tree (children first, so no pointer is used after its target is gone).
Breadth-first: level order with a queue
Level order visits the root, then every node at depth 1 from left to right, then depth 2, and so on. Recursion cannot do this directly, because the next node to visit is usually in a different subtree. A FIFO queue can:
levelOrder(root):
queue = empty
if root is not null: queue.enqueue(root)
while queue is not empty:
node = queue.dequeue()
visit(node)
if node.left is not null: queue.enqueue(node.left)
if node.right is not null: queue.enqueue(node.right)
On the sample: 8 4 12 2 6 10 14 1 5 7. A node's children join the back of the queue, behind every remaining node of the current level, so no node of depth d + 1 is visited before all nodes of depth d. Swap the queue for a stack and you get a depth-first order instead (node, right, left: a mirrored preorder, because the right child is pushed last and popped first), which is a good way to remember why the queue matters.
To process one level at a time (for example, to return a list per level), read the queue's size at the start of each round and dequeue exactly that many nodes before moving on.
Level order also finds the shallowest node that satisfies a condition: the first match it reaches is at the smallest depth. On graphs, the same idea is breadth-first search, which finds shortest paths measured in edges.
Costs
Let n be the number of nodes, h the height and w the largest number of nodes on one level.
| Traversal | Time | Extra space |
|---|---|---|
| Preorder, inorder, postorder (recursive) | Θ(n) | Θ(h) call stack |
| Level order (queue) | Θ(n) | Θ(w) queue |
Time. Every node is visited once, and each recursive call does constant work besides its two recursive calls. There are n calls on real nodes and n + 1 calls on null children (a binary tree with n nodes has n + 1 missing child slots), so about 2n + 1 calls in total: Θ(n). Level order enqueues and dequeues each node once: Θ(n).
Space. It depends on the tree's shape, which is the interesting part:
- A balanced tree has h ≈ log₂ n, so depth-first needs only Θ(log n) frames. Its last level holds about half the nodes, so level order can need Θ(n) queue space: (n + 1) / 2 nodes for a perfect tree.
- A degenerate tree (every node has one child, effectively a linked list) has h = n − 1. Depth-first needs Θ(n) frames, while level order never holds more than one node.
So neither is always cheaper. On the sample tree the call stack holds at most 4 nodes (8, 4, 2, 1), one more frame briefly for a null child, and the queue holds at most 5 nodes.
Deep trees: iterative traversals
The call stack is small and fixed. A degenerate tree with a hundred thousand nodes means a hundred
thousand nested calls. CPython stops at its recursion limit (1000 by default, see
sys.getrecursionlimit()) with RecursionError. Java throws StackOverflowError. In .NET a stack
overflow terminates the process and cannot be caught. In C++ it is undefined behaviour, usually a crash.
The fix is to keep your own stack on the heap:
preorderIterative(root): inorderIterative(root):
stack = [root] if root else [] stack = [], node = root
while stack: while node or stack:
node = stack.pop() while node: # go left as far as possible
visit(node) stack.push(node); node = node.left
if node.right: stack.push(node.right) node = stack.pop()
if node.left: stack.push(node.left) visit(node)
node = node.right
Preorder pushes the right child first so that the left one is popped first. Inorder keeps the path of nodes whose left subtree is still being processed. Postorder is the fiddliest: one common trick runs a "node, right, left" preorder and reverses the output, which gives "left, right, node". The extra space is still Θ(h), but on the heap, where it is limited by memory instead of the thread's stack size. (Morris traversal even gets inorder down to O(1) extra space by temporarily rewiring null right pointers; it is clever but rarely worth the complexity.)
Built-in trees and traversals
None of the four standard libraries has a general-purpose binary tree type you can build node by node. You write a small node class, as the teaching code does. What they do have:
| C# | Python | Java | C++ | |
|---|---|---|---|---|
| Balanced BST containers | SortedSet<T>, SortedDictionary<K,V> |
none in the standard library | TreeSet<E>, TreeMap<K,V> (red-black) |
std::set, std::map (usually red-black) |
| Iterating them yields | sorted order: an inorder walk | sorted order | sorted order | |
| Queue for level order | Queue<T> |
collections.deque |
ArrayDeque<E> |
std::queue<T> |
| Stack for iterative DFS | Stack<T> |
list |
ArrayDeque<E> |
std::vector<T> or std::stack<T> |
Details that matter:
- Sorted containers are trees. Iterating a
SortedSet<T>,TreeMap, orstd::mapin order is an inorder traversal performed for you, done iteratively with parent pointers or an internal stack. - Python's
os.walkis a tree traversal of the file system. Withtopdown=True(the default) it yields each directory before its subdirectories, which is preorder; withtopdown=Falseit yields each directory after them, which is postorder and is what you want for deleting a tree of folders. - Java's
ArrayDequeis the usual queue for BFS and stack for iterative DFS, but it rejectsnullelements, so never enqueue a missing child; check fornullfirst, as the teaching code does. - C++ ownership: the teaching
TreeNodeowns its children throughstd::unique_ptr, so destroying the root frees the whole tree. That destruction is itself recursive, one frame per level, so a very deep tree needs an iterative teardown, the same issue the linked list lesson shows.
The teaching implementation
Each language has a node class, a builder from the level-order format, three recursive depth-first
functions that append to an output list, and an iterative level-order function using the language's
queue (Queue<T>, deque, ArrayDeque, std::queue). The listings are checked against one shared
fixture of trees: empty, a single node, a left chain, a right chain, a full three-node tree, negatives,
and the sample BST.
Common mistakes
- Forgetting the base case, or checking
node.leftfor null but notnodeitself, which crashes on an empty tree. - Expecting inorder to sort any tree. It sorts only binary search trees.
- Using a stack for level order. You get a depth-first order instead.
- Recursing on deep or untrusted input: a degenerate tree overflows the call stack.
- Mixing up the input format: in the level-order list, children of a missing node are not listed,
so the positions are not simply
2i + 1and2i + 2once nulls appear. - Confusing depth and height conventions (edges vs nodes) when comparing results.
Edge cases
- Empty tree: every traversal returns an empty sequence; level order never enqueues anything.
- Single node: all four orders give that one value.
- Left chain
3 2 null 1: preorder 3 2 1, inorder and postorder 1 2 3. Depth-first space is Θ(n). - Right chain
1 null 2 null 3: preorder and inorder 1 2 3, postorder 3 2 1. - Duplicate values: traversals do not care; they visit nodes, not distinct values.
Worked practice
1. Give all four orders for the tree 1 2 3 4 5 null 6.
Answer
The tree: 1 has children 2 and 3; 2 has 4 and 5; 3 has only a right child, 6. Preorder: 1 2 4 5 3 6. Inorder: 4 2 5 1 3 6. Postorder: 4 5 2 6 3 1. Level order: 1 2 3 4 5 6.
2. Preorder is 3 9 20 15 7 and inorder is 9 3 15 20 7 (distinct values). Rebuild the tree.
Answer
Preorder's first value, 3, is the root. In the inorder list, everything left of 3 (9) is the left
subtree and everything right of it (15 20 7) is the right subtree. Recurse: the right subtree's
preorder is 20 15 7, so 20 is its root, with 15 on the left and 7 on the right. In level order:
3 9 20 null null 15 7. Preorder plus inorder always determines a binary tree with distinct values;
preorder plus postorder does not (a single child could be left or right).
3. Which order computes the height of every node, and why?
Answer
Postorder. A node's height is 1 + the larger of its children's heights (with −1 for an empty subtree under the edge convention), so both children must be finished before the node is processed.
4. A perfect binary tree has 1,023 nodes. How large do the call stack and the queue get?
Answer
Its height is 9 (2¹⁰ − 1 = 1,023 nodes on 10 levels), so recursion keeps at most 10 node frames, plus one for a null child. The last level holds 512 nodes, so level order's queue reaches about 512 entries. For a perfect tree, depth-first is far cheaper in memory; for a degenerate tree it is the other way round.
Summary
- Depth-first orders differ only in when the node is visited: before (pre), between (in) or after (post) its subtrees.
- Level order uses a FIFO queue to sweep the tree one depth at a time.
- All four are Θ(n) time. Depth-first uses Θ(h) extra space, level order up to Θ(w).
- Inorder sorts a BST; preorder copies and serializes; postorder combines children's results and frees trees.
- For deep trees, use an explicit stack instead of recursion.