Iterative inorder and preorder
Traverse a binary tree with an explicit stack instead of recursion: the same orders, but the stack that recursion hides is in plain view.
A recursive traversal really uses the call stack. Keep the stack ourselves and no recursion is needed, and the stack is in plain view.
Read the full explanation ↓- Time:
Θ(n) - Space:
O(h) for the stack - Horowitz–Sahni, chapter 5
A seven-node search tree; inorder 3 6 7 15 17 18 20 (sorted) and preorder 15 6 3 7 18 17 20.
class Node:def __init__(self, key):self.key = keyself.left = Noneself.right = Nonedef iterative(root):stack = []on_stack = [] # the keys of the nodes on the stack, for the picture# Inorder: go left as far as possible, pushing each node; then pop, visit, and go right.ino = []out = inonode = rootwhile node is not None or stack:if node is not None:stack.append(node)on_stack.append(node.key)node = node.leftelse:node = stack.pop()on_stack.pop()ino.append(node.key)node = node.right# Preorder: pop and visit; push the right child first so the left one comes out first.pre = []out = preif root is not None:stack.append(root)on_stack.append(root.key)while stack:node = stack.pop()on_stack.pop()pre.append(node.key)if node.right is not None:stack.append(node.right)on_stack.append(node.right.key)if node.left is not None:stack.append(node.left)on_stack.append(node.left.key)return ino, pre
Start
on_stack—
ino—
pre—
Local variables
Orange = changed in this step
root object
- key = 15
- left = Node(key=6, left=Node(key=3, left=None, right=None), right=Node(key=7, left=None, right=None))
- right = Node(key=18, left=Node(key=17, left=None, right=None), right=Node(key=20, left=None, right=None))
Call stack
- iterative()line 8
Step 1 of 145
Explanation
The idea
A recursive traversal really uses the call stack. Keep the stack ourselves and no recursion is needed, and the stack is in plain view.
- Inorder: go left as far as possible, pushing each node. On reaching null, pop one, visit it and go to its right subtree.
- Preorder: push the root; repeatedly pop one, visit it, and push its right child and then its left one, so the left comes out first.
Cost
Each node is pushed once and popped once: Θ(n). The stack grows to at most the tree's height h.
What to watch in the trace
on_stackis the stack's keys (the bottom on the left). Compare the left and the right chain.