One walk round the tree
This binary search tree holds 7 keys: smaller keys sit to the left, bigger to the right. A traversal visits every node exactly once. The question is in what order. Four standard orders give four different lists from the same tree.
Recursion walks the tree the same way every time: go left, come back, go right, come back. Follow the dot round the outside. It passes each node three times: on the way down, between its children, and on the way back up.
In Python the walk is a function that calls itself on the left child, then on the right. The print can sit in one of three slots: before both calls, between them, or after both. Each slot matches one pass.
Depth first
Pre-order prints a node on the first pass, before its children, so the root comes first: 40 20 10 30 60 50 70. Every parent is printed before its children, which is the order you need to copy a tree.
In-order prints on the second pass: after the whole left subtree, before the right one. In a binary search tree everything left is smaller, so the keys come out sorted: 10 20 30 40 50 60 70.
Post-order waits for the third pass, when both children are done: 10 30 20 50 70 60 40. The root comes last. Use it when a node needs its children finished first, like deleting a tree or adding up folder sizes.
All three orders are the same walk, so they cost the same. dfs runs once per node, plus once per empty child, which returns at once. 7 nodes have 8 empty children: 15 calls, 2n + 1. That is Θ(n) time.
Breadth first
Level order reads the tree row by row, top to bottom, left to right. The walk cannot do that: it dives down first. A queue can. It is a line: add at the back, take from the front. Start with the root in it.
Repeat: take the front node, print it, add its children at the back. Children wait behind everything already in line, so each row prints before the next: 40 20 60 10 30 50 70.
What happens
;; step 1/9 · tree
40
/ \
20 60
/ \ / \
10 30 50 70
n = 7 nodes, height 2
left subtree < node < right subtree
from collections import deque
class Node:
def __init__(self, key, left=None, right=None):
self.key, self.left, self.right = key, left, right
root = Node(40, Node(20, Node(10), Node(30)),
Node(60, Node(50), Node(70)))
The three passes are the times the recursion is at a node: when dfs(n) starts, when dfs(n.left) returns, and when dfs(n.right) returns. A real program prints in only one of the slots; the figure shows all three so you can compare them. Each call does O(1) work besides its two recursive calls, and a binary tree with n nodes has n + 1 empty child links, so dfs is called 2n + 1 times (15 here). CLRS Theorem 12.1 proves the same Θ(n) bound for the in-order walk.