Iterative traversals with an explicit stack

Video lessonComing soon

1 The call stack keeps a to-do list

The last lesson ended with a warning. On a chain of 10⁵ nodes, the recursion goes 10⁵ calls deep. The call stack has a fixed size, much smaller than the rest of memory, so it can overflow, and the program stops with a Runtime Error.

Here is what the call stack holds when the recursive inorder on our running tree reaches 4:

425136
Recursive inorder has reached 4
inorder(1)inorder(2)inorder(4)top →
call stack
124top →
our stack

Each paused call is a note that says "come back to this node later". inorder(1) still has to write 1 and then walk the subtree of 3. inorder(2) still has to write 2 and walk 5. Each call needs only its node and how far along it is.

So we can keep the notes ourselves. An explicit stack is a plain stack in our code that holds nodes. It lives in ordinary memory, where 10⁵ nodes are no trouble. A loop pops a note, does the work, and pushes new notes. This is an iterative traversal.

Each order writes a node at one of its three moments, and the notes must bring us back at the right one. Preorder needs nothing extra, inorder needs one more idea, and postorder needs two.

2 Preorder: pop, write, push right then left

Preorder writes a node the moment the walk arrives. So a note only has to say "this subtree is still to do". We push the root. Then, until the stack is empty, we pop a node, write it, and push its children as new notes.

The children go in right first. A stack hands back the last thing pushed, so the left child comes out first. Its whole subtree is written before the right child reaches the top. That is node, left, right.

Preorder with a stack
425136
Start: push the root, 1
1top →
pending

From step 2 to step 5, the 3 waits at the bottom while the whole left side runs. It is the note for "walk the right subtree of 1", the same job preorder(1) kept on the call stack.

We never push a null child. Each pop then has a real node to write.

C++

top, then pop. pop() removes the top but returns nothing, so we read it with top() first.

ArrayDeque as the stack. push and pop work on its front. It refuses null and throws, so the null checks before each push are needed.

A list is the stack. append pushes onto the end and pop() takes from the end, both in O(1).

An array is the stack. push adds to the end and pop takes from the end, both in O(1).

A slice is the stack. We read the last element, then cut it off with pending[:len(pending)-1].

while let ends the loop. pop() returns None on an empty Vec, which stops the loop. clone() on a child copies the Rc pointer, not the subtree.

Stack<TreeNode> has Push, Pop and Count. Pop on an empty stack throws, so the loop checks Count first.

3 Inorder: a node waits for its left side

Inorder writes a node only after its whole left subtree. So we cannot write a node when we first reach it. It waits on the stack, and a pointer current walks ahead. The loop repeats two moves:

  1. Go left. While current is not null, push it and step to its left child.
  2. Pop and go right. Pop a node and write it. Its left subtree is done: those nodes went on the stack after it, so they came off before it. Then set current to its right child.
Inorder with a stack
425136
Go left from 1: push 1, 2, 4
124top →
pending

The same run as a table, one row per round of the two moves:

Roundcurrent at startPushed going leftPopped and writtencurrent after
111, 2, 44null
2nullnothing25
3555null
4nullnothing13
53336
6666null

Each round writes one node. After round 4, the stack is empty but current is 3. So the loop runs while current is not null or the stack is not empty.

The inner loop is move 1, and the rest of the outer loop is move 2. An empty tree needs no special case: current is null and the stack is empty, so the loop never starts.

4 Postorder the easy way: a mirrored preorder, reversed

Postorder writes a node last, after both its subtrees. The last lesson warned that postorder is not preorder backwards: reversing node, left, right gives right, left, node.

We can turn it around. Postorder is left, right, node, so postorder backwards is node, right, left. That is preorder with the two children swapped, and we already have that loop. So we:

  1. Run the preorder loop, but push the left child first, so the right one comes out first.
  2. Reverse the list at the end.
136254
Node, right, left
452631
Reversed: the postorder

Next to the preorder code, only the two ifs swap places, and one line reverses the list in place.

5 Postorder with one stack and the last node written

The trick writes each node at the wrong moment and fixes the order at the end. Some interviewers ask for a real postorder, where each node is written at its third moment. That version builds on the inorder loop.

In inorder, the node on top had finished its left side, and we wrote it. In postorder, it must wait for its right side too. So a node reaches the top twice:

  • Back from the left. Its right side is still to do, so it stays on the stack and we go right.
  • Back from the right. Both sides are done, so we pop it and write it.

The stack cannot tell these apart, but one more variable can. lastWritten is the last node we wrote. A right child is the last node its own subtree writes. So if the top's right child is null or is lastWritten, its right side is done.

current = root
lastWritten = null
while current is not null or pending is not empty:
    while current is not null:
        push current
        current = current.left
    node = top of pending
    if node.right is null or node.right is lastWritten:
        pop
        write node.val
        lastWritten = node
    else:
        current = node.right

On our tree, each row is one look at the top of the stack:

Stack (bottom to top)top.rightlastWrittenRight done?What happens
1, 2, 4nullnullyeswrite 4
1, 254nogo right: push 5
1, 2, 5null4yeswrite 5
1, 255yeswrite 2
132nogo right: push 3
1, 362nogo right: push 6
1, 3, 6null2yeswrite 6
1, 366yeswrite 3
133yeswrite 1

The output is 4 5 2 6 3 1. Node 2 is on top in rows 2 and 4, and node 3 in rows 6 and 8: once to go right, and once to be written.

6 What the stack holds, and the cost

Each order keeps a different kind of note on the stack:

OrderA node on the stack waits forIt is written when
Preorderits turn to startit is popped
Inorderits left subtree to finishit is popped
Postorder, one stackboth subtrees to finishits right side is done

Time. Every node is pushed once and popped once. In the one-stack postorder, a node can sit on top twice, which is still a fixed amount of work. Reversing the list is one more pass. So every version takes O(n) time.

Space. The stack holds about one node per level of the tree, so it takes O(h) space, where h is the height. That is the same as the recursion. The difference is where it lives. On a chain of 10⁵ nodes, our stack holds 10⁵ nodes in ordinary memory, and the run finishes normally.

The next lesson, Morris traversal, gets the space down to O(1) by borrowing the tree's own null pointers.

7 Mistakes and edge cases

  • Pushing left before right in preorder. The right subtree then comes out first. On our tree, the output is 1 3 6 2 5 4, and that is Wrong Answer.
  • Not moving to the right child in inorder. Without current = node.right, current stays null, and every right subtree is skipped. Our tree gives 4 2 1. Code that pops straight into current and forgets the move is worse: the same node goes back on the stack every round, the loop never ends, and it gets TLE.
  • Pushing null. Pushing a missing child puts null on the stack. When it comes out, reading its value crashes with a Runtime Error. In preorder, the empty tree [] crashes the same way if the root goes on the stack without a check.
  • Reversing the wrong preorder. Reversing the normal preorder, with right pushed first, gives 6 3 5 4 2 1. Postorder needs the mirrored one, with left pushed first.
  • Comparing values instead of nodes. In the one-stack postorder, node.right is lastWritten must compare the nodes themselves. On the tree [2, 5, 5], a value check takes the right 5 as done after the left 5 is written. The output is 5 2 instead of 5 5 2.

8 When to use an explicit stack

The sign is a problem that must visit every node in a set order. The recursive version is shorter, so we reach for the stack when:

  • The tree can be deep. A chain of 10⁵ nodes overflows the call stack. The loop keeps its stack in ordinary memory, so it runs fine.
  • The walk must pause. The stack holds the walk's place, so the walk can stop after any node and carry on later. A tree iterator that hands out the next inorder value on each call keeps this stack between calls.
  • The question forbids recursion. Interviewers often ask for inorder or postorder this way.

The next problem asks for all three orders in one walk. For it, a note can carry the node and which of its three moments comes next.

Before writing an iterative traversal, ask what each node on the stack is waiting for. The answer says when to pop it and when to write it.

Practice it

Finished this lesson?

Mark it read and it is ticked on the roadmap and in the list.

Article

Send feedback

Thank you for helping. We read every report and fix what is wrong.

How do you feel about oneby7?

Sign in to oneby7

Keep your progress, your streak and your code, on any device.

New here? This creates your account too.