Tree traversals
In-order, pre-order, post-order and level-order, and what each is for.
Before you start
A tree has no single "correct" reading order. Unlike an array — where you start at index 0 and walk to the end — a tree branches, so you have to decide which branch to take first and when to record the node you're standing on.
There are four standard answers. Three of them are depth-first: go as deep as you can, and differ only in **when** you record the current node — before its children (pre-order), between them (in-order), or after them (post-order). The fourth is breadth-first: finish an entire level before starting the next.
Each order is the right tool for a different job, and this lesson walks all four across the same tree so you can watch the output sequences diverge.
Binary tree
same tree, four different reading ordersOutput so far
nothing visited yet6 nodes. Four traversals will emit them in four different orders.
Step 1 of 8. One tree, four readings. This is the tree every stage will use. Node 1 is the root; 2 and 3 are its children; 4, 5 and 6 are leaves. Nothing has been visited yet. What changes between traversals is purely the **order** in which these six nodes get recorded — not the tree itself.
Step 01 / 08
One tree, four readings
This is the tree every stage will use. Node 1 is the root; 2 and 3 are its children; 4, 5 and 6 are leaves.
Nothing has been visited yet. What changes between traversals is purely the **order** in which these six nodes get recorded — not the tree itself.
struct Node { int val; struct Node *left, *right; };void inorder(struct Node *n) { /* left, self, right */ if (!n) return; inorder(n->left); visit(n); inorder(n->right);}void preorder(struct Node *n) { /* self, left, right */ if (!n) return; visit(n); preorder(n->left); preorder(n->right);}void postorder(struct Node *n) { /* left, right, self */ if (!n) return; postorder(n->left); postorder(n->right); visit(n);}void levelorder(struct Node *root) { /* breadth, by depth */ Queue q; enqueue(&q, root); while (!empty(&q)) { struct Node *n = dequeue(&q); visit(n); if (n->left) enqueue(&q, n->left); if (n->right) enqueue(&q, n->right); }}