Four ways to walk a binary tree
A traversal visits every node of a binary tree once: preorder, inorder and postorder differ only in where the visit line sits in the recursion, and level order goes one level at a time with a deque.
Last lesson's size, height and total all did the same thing underneath: visit every node once. Printing a tree, saving it to a file, copying it, checking that it is a binary search tree: none of it works without this, and the only difference is who gets visited first. A binary tree has four common orders: preorder, inorder, postorder and level order. The same 6-node tree gives four different sequences in the four orders; and lesson 3 shows that any two of them are enough to draw the whole tree back exactly.
Preorder, inorder, postorder
All three orders put "the left subtree before the right subtree"; they differ only in where the root goes:
- preorder: root, left, right;
- inorder: left, root, right;
- postorder: left, right, root.
As recursion, the three functions differ only in where the line out.append(node.val) sits. Here is last lesson's tree [1, 2, 3, 4, 5, None, 6] again:
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def build(vals):10 if not vals or vals[0] is None:11 return None12 root = TreeNode(vals[0])13 q = deque([root])14 i = 115 while q and i < len(vals):16 node = q.popleft()17 if vals[i] is not None:18 node.left = TreeNode(vals[i])19 q.append(node.left)20 i += 121 if i < len(vals) and vals[i] is not None:22 node.right = TreeNode(vals[i])23 q.append(node.right)24 i += 125 return root26 27def preorder(node, out):28 if node:29 out.append(node.val) # root30 preorder(node.left, out) # left31 preorder(node.right, out) # right32 return out33 34def inorder(node, out):35 if node:36 inorder(node.left, out)37 out.append(node.val) # root in the middle38 inorder(node.right, out)39 return out40 41def postorder(node, out):42 if node:43 postorder(node.left, out)44 postorder(node.right, out)45 out.append(node.val) # root last46 return out47 48root = build([1, 2, 3, 4, 5, None, 6])49print("preorder ", preorder(root, []))50print("inorder ", inorder(root, []))51print("postorder", postorder(root, []))
preorder [1, 2, 4, 5, 3, 6] inorder [4, 2, 5, 1, 3, 6] postorder [4, 5, 2, 6, 3, 1]
Each sequence has one feature worth remembering: the first in preorder is always the root; the last in postorder is always the root; and in inorder, everything left of the root is the left subtree and everything right of it is the right subtree. Rebuilding a tree in lesson 3 rests on exactly these three facts.
2 has only a right child 4, and 3 has only a left child 5. What does the postorder walk print?
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def post(node):8 if node:9 post(node.left)10 post(node.right)11 print(node.val, end=" ")12 13root = TreeNode(1, TreeNode(2, None, TreeNode(4)),14 TreeNode(3, TreeNode(5)))15post(root)16print()
2 4 1 5 3 is inorder, and 1 2 4 3 5 is preorder.A's left child is B and its right child is C; B's children are D and E; C has only a left child, F. What is this tree's inorder traversal?
A B D E C F is preorder and D E B F C A is postorder.A tree's postorder traversal is D E B F C A. Which node is the root?
With a stack of your own
During recursion, Python keeps track of "what is left to do when I come back": that is the call stack. Replace it with a list of your own and the recursion depth limit no longer applies.
Preorder is the simplest: the stack holds "nodes not visited yet". Pop one, visit it, and push its children. A stack is last in, first out, so to walk the left first you must push the right child first and then the left.
stack
1 root3 right2 left5 right4 left6 rightPush in the wrong order and the result becomes "root, right, left":
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def preorder_iter(root, left_first):8 out = []9 stack = [root] if root else []10 while stack:11 node = stack.pop()12 out.append(node.val)13 kids = [node.right, node.left] if left_first else [node.left, node.right]14 for kid in kids: # pushed first, popped last15 if kid:16 stack.append(kid)17 return out18 19root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),20 TreeNode(3, None, TreeNode(6)))21print("right pushed first, then left", preorder_iter(root, True))22print("left pushed first, then right", preorder_iter(root, False))
right pushed first, then left [1, 2, 4, 5, 3, 6] left pushed first, then right [1, 3, 6, 2, 5, 4]
"Root, right, left" has its use, though: reversed it is "left, right, root", which is exactly postorder. Inorder needs one more pointer, cur: first go left as far as you can, pushing every node you pass; at the end, pop one and visit it, then turn to its right subtree.
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def inorder_iter(root):8 out, stack, cur = [], [], root9 while cur or stack:10 while cur: # go left all the way, keeping what we pass11 stack.append(cur)12 cur = cur.left13 cur = stack.pop() # its left is done: visit it14 out.append(cur.val)15 cur = cur.right # then its right subtree16 return out17 18def postorder_iter(root):19 out = []20 stack = [root] if root else []21 while stack:22 node = stack.pop()23 out.append(node.val) # root, right, left24 if node.left:25 stack.append(node.left)26 if node.right:27 stack.append(node.right)28 return out[::-1] # reversed: left, right, root29 30root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),31 TreeNode(3, None, TreeNode(6)))32print(inorder_iter(root))33print(postorder_iter(root))34 35chain = None36for v in range(3000, 0, -1): # a line 3000 levels deep: recursion would raise RecursionError37 chain = TreeNode(v, chain)38print(len(inorder_iter(chain)), inorder_iter(chain)[:3])
[4, 2, 5, 1, 3, 6] [4, 5, 2, 6, 3, 1] 3000 [3000, 2999, 2998]
The last line walks a tree 3000 levels deep (every node has only a left child): a stack of our own holds 3000 nodes without any trouble, while recursion would have passed its limit long before.
Writing preorder (root, left, right) with your own stack: after popping a node and visiting it, how should its children be pushed?
Push the left child first, then the right, and reverse the result at the end. What does it print?
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7root = TreeNode(1, TreeNode(2), TreeNode(3, TreeNode(4), TreeNode(5)))8out = []9stack = [root]10while stack:11 node = stack.pop()12 out.append(node.val)13 if node.left:14 stack.append(node.left)15 if node.right:16 stack.append(node.right)17print(out, out[::-1])
Inorder without recursion
✓Complete inorder_iter(root): use a list as a stack and return the inorder traversal. No recursion.
[4, 2, 5, 1, 3, 6] [1, 3, 2] []
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def inorder_iter(root):8 out, stack, cur = [], [], root9 # push all the way left; at the end pop one and visit it; then turn to its right subtree10 return out11 12root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),13 TreeNode(3, None, TreeNode(6)))14print(inorder_iter(root))15print(inorder_iter(TreeNode(1, None, TreeNode(2, TreeNode(3)))))16print(inorder_iter(None))
Level order: one level at a time
Level order starts at the root and visits one level at a time, left to right within each level: exactly the order the list was read in when last lesson built the tree. It uses a queue, not a stack: the node queued first is visited first, and visiting a node sends its children to the back, so the whole of level 2 comes out before level 3 starts.
head1q = deque([root])2while q:3 node = q.popleft()4 out.append(node.val)5 if node.left:6 q.append(node.left)7 if node.right:8 q.append(node.right)
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def level_order(root):10 out = []11 q = deque([root] if root else [])12 while q:13 node = q.popleft()14 out.append(node.val)15 if node.left:16 q.append(node.left)17 if node.right:18 q.append(node.right)19 return out20 21root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),22 TreeNode(3, None, TreeNode(6)))23print(level_order(root))24print(level_order(None))
[1, 2, 3, 4, 5, 6] []
The queue is always a deque: list.pop(0) shifts every item behind it each time (the queue lesson in chapter 2 counted it). To know which level each node is on (for example, one line per level), lesson 8's pattern adds an inner for _ in range(len(q)) to the loop.
| Traversal | Order | Result for the example | Stack or queue | Used for |
|---|---|---|---|---|
| Preorder | root, left, right | 1 2 4 5 3 6 | stack | copying a tree, writing a tree out as text |
| Inorder | left, root, right | 4 2 5 1 3 6 | stack (plus cur) | a binary search tree in sorted order |
| Postorder | left, right, root | 4 5 2 6 3 1 | stack (root-right-left, reversed) | children before yourself: height, freeing, evaluating expressions |
| Level order | level by level | 1 2 3 4 5 6 | queue (deque) | fewest steps, per-level work, the right side view |
All four visit each node once: O(n) time; the stack or queue holds at most O(h) nodes or O(the width of one level) at a time.
In interviews: "Write inorder traversal without recursion" comes up nearly every time; remember its three moves: "push all the way left, pop and visit, turn right". Another common one is "how do the non-recursive preorder and postorder relate": root-right-left preorder, reversed, is postorder.
A's left child is B and its right child is C; B's children are D and E; C has only a left child, F. What is this tree's level-order traversal?
Why does level order use a deque for its queue rather than list.pop(0)?
Level order
✓Complete level_order(root): visit the tree level by level with a deque and return a list of the nodes' values. An empty tree returns [].
[3, 9, 20, 15, 7] [1, 2, 3, 4] []
1from collections import deque2 3class TreeNode:4 def __init__(self, val, left=None, right=None):5 self.val = val6 self.left = left7 self.right = right8 9def level_order(root):10 out = []11 # the root joins the queue; each time popleft one, visit it, and append its children at the back12 return out13 14root = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))15print(level_order(root))16print(level_order(TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4))))))17print(level_order(None))
How you write it at work
The standard library has no tree, so it has no ready-made traversal either. The Python habit is to write a traversal as a generator: yield hands out one value and pauses, carrying on next time a value is wanted; yield from passes on whatever the subtree's generator hands out. A tree can then go straight into for, list, sum, max and sorted:
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def inorder(node):8 if node:9 yield from inorder(node.left)10 yield node.val11 yield from inorder(node.right)12 13root = TreeNode(1, TreeNode(2, TreeNode(4), TreeNode(5)),14 TreeNode(3, None, TreeNode(6)))15print(list(inorder(root)))16print(sum(inorder(root)), max(inorder(root)), sorted(inorder(root), reverse=True))17 18it = inorder(root)19print(next(it), next(it)) # one step only when asked20print(next(x for x in inorder(root) if x > 4)) # stops when found, without walking the whole tree
[4, 2, 5, 1, 3, 6] 21 6 [6, 5, 4, 3, 2, 1] 4 2 5
- Generators are lazy: if you only want the first node that matches, the rest is never walked.
- Each value a recursive generator hands out passes through every
yield frombetween the root and that node, so the total cost is O(n·h); for a deep tree, write the generator with last section's stack instead (yieldinside the loop) and you are back to O(n). - Level order always uses
collections.deque, neverlist.pop(0). - When you don't know how deep a tree may be (user data, parsed nested structures), use your own stack or queue rather than recursion.
A generator plus next, asking only for the first number over 5. What does it print?
1seen = []2 3def walk(xs):4 for x in xs:5 seen.append(x)6 yield x7 8first = next(x for x in walk([3, 8, 1, 9]) if x > 5)9print(first, seen)
next asks for a value. At 8 the condition holds, and 1 and 9 are never even looked at, so seen is just [3, 8].Summary
Four traversals: every node once, only the order differs
- Preorder root-left-right, inorder left-root-right, postorder left-right-root: the recursion differs only in where append goes
- Preorder without recursion: pop and visit, push right then left; postorder = root-right-left reversed
- Inorder without recursion: push all the way left, pop and visit, turn to the right subtree
- Level order with a deque: take from the front and visit, children join at the back
- Written as a generator with yield from, a tree goes into for, list, sum and max
1def inorder(node):2 if node:3 yield from inorder(node.left)4 yield node.val5 yield from inorder(node.right)