Walking a tree with recursion
After this: Follow preorder with the call stack and say why each node is visited once.
On this page · 10 sections · 3 checks
You can now read a tree and build one in code. Next you will want to use it: print every value, add up the values, or find the largest one. For all of these, a program must go through every node. Going through every node once is called a . In this tutorial we also call it a walk.
In a list, this is a plain loop, because each item has one next item. A tree is harder. A node can have a left child and a right child. If you go left, how do you come back later for the right?
Recursion solves this for us. This lesson shows how.
A short reminder
The recursion tutorial showed these ideas. Here they are again in brief.
- A recursive function calls itself on a smaller input.
- A is an input it can answer without calling itself. It stops the recursion.
- Each call that is running or waiting has a . The frame remembers the call's inputs and which line it has reached.
- The frames sit on the . A new call adds a frame on top. When a call ends, its frame is removed, and the call below continues from the line where it stopped.
The idea: walk the subtrees
The last lesson showed that the left side of a node is a tree, and so is the right side. Each is smaller than the tree it sits in. That is the "smaller input" recursion needs. An empty subtree is the base case.
So here is how to walk a tree.
- If there is no node here, stop.
- Deal with this node.
- Walk the left subtree.
- Walk the right subtree.
Dealing with a node is called it. In this lesson, a visit adds the node's value to a list, so that we can see the order afterwards.
The smallest example
Here is the walk on the three-node tree.
- The walk starts at node 1. Visit it. The list is now 1.
- Walk the left subtree, which is node 2. Visit it. The list is now 1, 2.
- Node 2 has no children. Both its subtrees are empty, so each of those walks stops at once. The walk of node 2 is finished.
- We are back at node 1, and it still has its right side to do. Walk the right subtree, which is node 3. Visit it. The list is now 1, 2, 3.
- Node 3 has no children, so its walk is finished.
- We are back at node 1. Both sides are done, so the whole walk is finished.
Look at step 4. How did the program know to come back to node 1 and go right? The frame for node 1 stayed on the call stack the whole time. It was paused on the line that walks the left subtree. When that call ended, the frame continued with its next line, which walks the right subtree.
That answers the question at the top. You go left first, and the call stack remembers that the right side is still to do.
The code
def preorder(node, out): if node is None: # an empty subtree: nothing to do return out.append(node.value) # visit: before either child preorder(node.left, out) # the whole left subtree preorder(node.right, out) # then the whole right subtreestatic void preorder(Node node, List<Integer> out) { if (node == null) return; // an empty subtree: nothing to do out.add(node.value); // visit: before either child preorder(node.left, out); // the whole left subtree preorder(node.right, out); // then the whole right subtree}Here is how to read it.
- The first check is the base case. If the node is Nonenull, the subtree is empty, so the function returns.
- The highlighted line is the visit. It adds this node's value to the list
out. - The last two lines are the recursive calls, left first and then right.
outis the same list in every call, so all the visits add to one list.
Here it is on the example tree.
visited = []preorder(root, visited)print(visited)[1, 2, 4, 5, 3, 6]
List<Integer> visited = new ArrayList<>();preorder(root, visited);System.out.println(visited);[1, 2, 4, 5, 3, 6]
This order, a node first and then its subtrees, is called . "Pre" means "before": the node comes before its children.
The stack, step by step
Here is the same walk with the call stack beside it. Each number in the stack column is the frame for that node. The oldest frame is on the left.
| What happens | Stack | Visited so far |
|---|---|---|
| Enter 1 and visit it | 1 | 1 |
| Enter 2 and visit it | 1, 2 | 1 2 |
| Enter 4 and visit it | 1, 2, 4 | 1 2 4 |
| Leave 4 | 1, 2 | 1 2 4 |
| Enter 5 and visit it | 1, 2, 5 | 1 2 4 5 |
| Leave 5 | 1, 2 | 1 2 4 5 |
| Leave 2 | 1 | 1 2 4 5 |
| Enter 3 and visit it | 1, 3 | 1 2 4 5 3 |
| Enter 6 and visit it | 1, 3, 6 | 1 2 4 5 3 6 |
| Leave 6 | 1, 3 | 1 2 4 5 3 6 |
| Leave 3 | 1 | 1 2 4 5 3 6 |
| Leave 1 | (empty) | 1 2 4 5 3 6 |
Now read the visited list in three parts: 1, then the whole subtree at 2 (2, 4, 5), then the whole subtree at 3 (3, 6).
Every node once
Notice that the code keeps no record of which nodes it has seen, and it does not need one. The only way to reach a node is by the one link from its parent, and the parent's call follows that link once. So each node gets one call and one visit. Six nodes means six visits.
This gives us the cost of a walk. In these tutorials, cost means the number of steps. A walk costs O(n), which means the work grows at the same rate as the number of nodes: twice the nodes, twice the visits. This is true whatever the shape of the tree. Counting steps explains O(n) if you have not met it.
How deep the stack gets
The shape of the tree does change one thing: how many frames wait on the stack. Look at the table again. The waiting frames are always the path from the root to the current node. While 4 is being visited, the stack holds 1, 2 and 4. That is three frames, which is the height plus one.
So a tall tree means a deep stack. The last lesson of this tutorial shows when that becomes a problem.
Watch it happen
Step through one preorder walk. The Stack band is the call stack from the table above. The Visited strip fills in as nodes are visited.
- Preorder traversalRun Preorder and step through it. Each call adds a frame to the Stack band, and each return removes one. The Visited strip fills in as nodes are visited.
Run an operation to begin.
Check yourself
Preorder visits 5. Which node does it visit after that?
During preorder of the example tree, what is the largest number of frames the Stack band shows at once?
preorder keeps no record of the nodes it has seen, yet every node is visited exactly once. Why?
Connect
- Write preorder: stop at an empty subtree, visit the node, then walk left and walk right.
- Say why every node is visited exactly once: each node has one parent, so only one call ever reaches it.
- Say how deep the call stack gets: one frame for each node on the path from the root, so at most the height + 1, counting real nodes.