Three problems that walk a whole tree in a fixed order without recursion. The move: replace the call stack with your own stack, and decide what it holds.
You work on a video app, a map app and a platform of services. Each one keeps its data in a tree, and each one needs a flat list of the nodes in a fixed order. The three problems on this street are the three classic orders.
All three visit every node once. They differ in one choice: when to visit a node, compared with the nodes below it.
| Problem | The node is visited | The stack holds |
|---|---|---|
| Inorder walk of the category tree | after its left side, before its right side | the path of nodes whose left side is still open |
| Preorder walk with the depth | before both sides | the subtrees still to visit, with their depth |
| Postorder walk with a stack | after both sides | the subtrees still to expand, until the list is reversed |
The problems add a condition that decides how you must write them. The trees can have 100,000 nodes, and some are one long chain. A recursive walk uses one call frame for each level, so a long chain breaks it.
That is not a guess. The recursive inorder walk, written as in the Academy, runs on a left chain of 900 nodes in Python. A chain of 1,500 nodes raises a recursion error, because the default limit is 1,000 nested calls.
A recursive walk keeps its work on the call stack: each frame is a node whose visit is not finished. You can keep that work on a stack that you own. Decide what the stack holds, and each loop step pops one piece of work.
For preorder, a piece is a whole subtree, so pop a node, visit it, and push its two children. For inorder, a piece is a node that waits for its left side. Push every node on the way down to the left, and visit one when it pops.
The stack holds exactly the work that has not been done yet, with the next piece on top. Each pop does one piece and pushes the pieces it creates, the last one needed first.
The stack gives back the last item first. So in preorder you push the right child, then the left child: the left child comes off first.
Here is an inorder walk on a small tree. The codes are [4, 9, 2, 7, 1, 8], node 0 is the top, and left and right hold the children, with -1 for none.
Exercise · Predict the output: The iterative inorder walk. The tree has the codes 4, 9, 2, 7, 1, 8. Node 0 has the children 1 and 2, node 1 has 3 and 4, and node 2 has only a right child, 5. What does this print?
values = [4, 9, 2, 7, 1, 8]
left = [1, 3, -1, -1, -1, -1]
right = [2, 4, 5, -1, -1, -1]
stack = []
node = 0
out = []
while node != -1 or stack:
while node != -1:
stack.append(node)
node = left[node]
node = stack.pop()
out.append(values[node])
node = right[node]
print(*out)Inorder with a stack: push the whole left path, pop to visit a node, then go to its right child.
Preorder carries one more thing: the depth of each node. Push a pair, the node and its depth, and give both children the depth of their parent plus one.
Exercise · Find the bug: The depth of the right child. This lists the depth of every node in preorder, from a stack of node and depth pairs. For one tree it gives a wrong depth. Which line is wrong?
def preorder_depths(values, left, right):
depths = []
stack = [(0, 0)] if values else []
while stack:
node, depth = stack.pop()
depths.append(depth)
if right[node] != -1:
stack.append((right[node], depth))
if left[node] != -1:
stack.append((left[node], depth + 1))
return depthsThe Academy lessons Trees and binary search trees and Tree recursion walk a tree with recursion. The lessons The call stack and Stacks show what a frame is and what a stack does. This street does not teach those again. It changes three things.
The stack is yours. A call frame holds a node and the place where the visit stopped. Your stack holds exactly that, but you choose it. For inorder it holds nodes, for preorder it holds nodes with their depth.
The size of the stack follows the height. On a left chain of 100,000 nodes the inorder stack grows to 100,000. On a complete tree of the same size it never holds more than 17. The time is always n, and the memory is the height of the tree.
Postorder needs a trick. A node must come after both sides, so a plain pop does not work. Walk node, right side, left side, which is the preorder loop with the children pushed left first, and reverse the output. On the tree above it gives 7, 1, 9, 8, 2, 4, and the recursive version gives the same list.
One mistake runs through the whole street. Push the left child first in preorder, and the outline is mirrored. On the tree above it reads 4, 2, 8, 9, 1, 7 instead of 4, 9, 7, 1, 2, 8.
Exercise · Break it: The inorder walk that visits too early. This inorder walk visits each node when it pushes it on the way down. Find a tree where its list is not in inorder.
def inorder_walk(values, left, right):
out = []
stack = []
node = 0 if values else -1
while node != -1 or stack:
while node != -1:
out.append(values[node])
stack.append(node)
node = left[node]
node = stack.pop()
node = right[node]
return outPush the left child first in preorder and the outline is mirrored. Push the right child first.
Solve them in this order. Inorder uses the path-down-the-left stack, preorder adds the depth, and postorder uses the reversal.
Before you code each problem, write two lines: when is the node visited, and what does one stack item mean? Then run a chain of 100,000 nodes before you submit. A recursive solution will fail it.
Give each problem about 20 minutes. Draw the tree with five or six nodes, and write the expected order by hand. Compare it with your output before you test a large input.
Test three trees on every rung: an empty tree, a left chain and a right chain. The empty tree catches a stack that starts with node 0 when there is no node. The two chains catch a stack that grows with the wrong shape.
When an order is wrong, check which child you push first. In every walk on this street, one wrong push order mirrors the whole output.
Checkpoint · Traversals
Q1/5 What is the only difference between inorder, preorder and postorder?
Answer: B
All three visit every node once. Preorder visits a node before both sides, inorder between them, and postorder after both.
Q2/5 An iterative preorder walk pops a node and visits it. In which order should it push the two children?
Answer: B
A stack returns the last item pushed first. Pushing the right child first makes the left child come off first, and the output is node, left side, right side.
Q3/5 Why does a recursive walk fail on a chain of 1,500 nodes in Python, and what does an explicit stack change?
Answer: B
The walk still takes n steps with a stack. What changes is where the waiting work lives: in a list on the heap instead of in call frames.
Q4/5 How large does the inorder stack grow on a left chain of 100,000 nodes?
Answer: C
Inorder pushes every node on the way down the left path before it visits any of them. The stack holds as many nodes as the tree is tall, and a chain is as tall as it is long.
Q5/5 How do you produce a postorder list with the preorder loop?
Answer: B
Reversed, the order node, right side, left side reads left side, right side, node, which is postorder.
Review cards from this lesson.
A few questions, then explain the idea back in your own words. Your tutor marks it. Quiz and explain back.