The four traversals of a binary tree
Traversing a binary tree visits every node in one of four usual orders: preorder (root, left, right), inorder (left, root, right) and postorder (left, right, root), which differ only in where the root goes, and level order, one level at a time with a queue.
Walk an array from start to end and there is only one order. A tree is different: at a node, do you handle the node itself first, or go left first, then right? Each choice gives a different sequence, and nearly every exam hands you a tree and asks for its traversals.
Preorder, inorder, postorder: only "this node" moves
All three recursive traversals do "the left subtree, then the right subtree". They differ only in when the root is visited:
- Preorder (root, left, right): visit this node, then go left, then right.
- Inorder (left, root, right): go left, then visit this node, then go right.
- Postorder (left, right, root): go left, then right, and visit this node last.
1void preorder(Node *t) {2 if (t == NULL) return;3 printf("%d ", t->val); // root4 preorder(t->left); // left5 preorder(t->right); // right6}
Inorder and postorder just move the printf line between the two calls, or after them.
The other two for the same tree: inorder 4 2 5 1 3 6 (every node after its left subtree and before its right), postorder 4 5 2 6 3 1 (the root always last).
Write down this tree's preorder traversal.
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
Same tree: write down its inorder traversal.
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
Write down this tree's postorder traversal.
1 A2 / \3 B C4 \ /5 D E6 /7 F
Fill in the two blanks so in becomes an inorder traversal: left, then the node itself, then right. The tree is the one from the first picture, so the program should print 4 2 5 1 3 6.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v; n->left = l; n->right = r;12 return n;13}14 15void in(Node *t) {16 if (t == NULL) return;17 ;18 printf("%d ", t->val);19 ;20}21 22int main(void) {23 Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),24 node(3, NULL, node(6, NULL, NULL)));25 in(t);26 printf("\n");27 return 0;28}
printf sits between the two recursive calls, with the left one before it and the right one after. Swap the blanks and you get right, root, left: 6 3 1 5 2 4.Write postorder
✓Finish post: left, right, and print this node last.
1 6 3 14 10 8
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v; n->left = l; n->right = r;12 return n;13}14 15void post(Node *t) {16 // an empty tree returns; otherwise left first, then right, then printf("%d ", t->val)17}18 19int main(void) {20 Node *t = node(8, node(3, node(1, NULL, NULL), node(6, NULL, NULL)),21 node(10, NULL, node(14, NULL, NULL)));22 post(t);23 printf("\n");24 return 0;25}
Expression trees: three traversals, three notations
The expression (3 + 4) * 5 can be stored as a tree: operators at the inner nodes, numbers at the leaves. Its three traversals are exactly the prefix, infix and postfix forms; postfix is the kind Chapter 2 evaluated with a stack.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 char val;6 struct Node *left, *right;7} Node;8 9Node *node(char v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v;12 n->left = l;13 n->right = r;14 return n;15}16 17void pre(Node *t) {18 if (!t) return;19 printf("%c ", t->val);20 pre(t->left);21 pre(t->right);22}23 24void in(Node *t) {25 if (!t) return;26 in(t->left);27 printf("%c ", t->val);28 in(t->right);29}30 31void post(Node *t) {32 if (!t) return;33 post(t->left);34 post(t->right);35 printf("%c ", t->val);36}37 38int main(void) {39 // (3 + 4) * 540 Node *t = node('*', node('+', node('3', NULL, NULL), node('4', NULL, NULL)), node('5', NULL, NULL));41 printf("preorder: ");42 pre(t);43 printf("\ninorder: ");44 in(t);45 printf("\npostorder: ");46 post(t);47 printf("\n");48 return 0;49}
preorder: * + 3 4 5 inorder: 3 + 4 * 5 postorder: 3 4 + 5 *
Notice that inorder prints 3 + 4 * 5: the brackets are gone, and by the usual rules 4 * 5 comes first, which changes the meaning. Infix needs brackets; prefix and postfix are never ambiguous without them, which is why computers like postfix.
An inorder traversal of this tree (B has only a left child, D). What does it print?
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 char val;6 struct Node *left, *right;7} Node;8 9Node *node(char v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v; n->left = l; n->right = r;12 return n;13}14 15void in(Node *t) {16 if (!t) return;17 in(t->left);18 printf("%c", t->val);19 in(t->right);20}21 22int main(void) {23 // A24 // B C25 // D E F26 Node *t = node('A', node('B', node('D', NULL, NULL), NULL),27 node('C', node('E', NULL, NULL), node('F', NULL, NULL)));28 in(t);29 printf("\n");30 return 0;31}
What is this expression tree's postorder traversal (its postfix expression)?
1 *2 / \3 3 +4 / \5 4 5
* 3 + 4 5 is preorder (prefix), and 3 * 4 + 5 is inorder, which without brackets means (3 × 4) + 5. 3 4 + 5 * is the tree for (3 + 4) × 5.What is the value of the postfix expression 2 3 4 * +? (Read left to right: numbers are pushed; an operator pops two numbers and pushes the result.)
* pops 4 and 3 and pushes 12; + pops 12 and 2 and pushes 14. Its expression tree has + at the root, 2 on the left and 3 * 4 on the right: 2 + 3 × 4 in infix.Level order: one level at a time, with a queue
Level order starts at the root and goes one level at a time, left to right on each. It isn't recursive; it uses a queue: put the root in; each time take one node out, visit it, and put its left and right children in (if they aren't NULL). First in, first out, so an upper level always comes out before the next.
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v; n->left = l; n->right = r;12 return n;13}14 15void level(Node *t) {16 Node *q[100];17 int head = 0, tail = 0;18 if (t) q[tail++] = t;19 while (head < tail) {20 Node *x = q[head++]; // out of the queue21 printf("%d ", x->val);22 if (x->left) q[tail++] = x->left; // its children in23 if (x->right) q[tail++] = x->right;24 }25 printf("\n");26}27 28int main(void) {29 Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),30 node(3, NULL, node(6, NULL, NULL)));31 level(t);32 return 0;33}
1 2 3 4 5 6
| Traversal | Order | How | This tree |
|---|---|---|---|
| Preorder | root left right | recursion, visit first | 1 2 4 5 3 6 |
| Inorder | left root right | recursion, visit in between | 4 2 5 1 3 6 |
| Postorder | left right root | recursion, visit last | 4 5 2 6 3 1 |
| Level order | level by level | a queue | 1 2 3 4 5 6 |
All four visit each node once, O(n). The three recursive ones use the call stack, as deep as the tree is tall; level order uses a queue, holding at most one level at a time.
In exams: a quick way to write preorder by hand: start at the root and trace around the outside of the tree, counterclockwise, writing a node down the first time you pass it; inorder is when you pass underneath it, postorder the last time you pass it. The last in postorder and the first in preorder are always the root.
Write down this tree's level-order traversal.
1 A2 / \3 B C4 / \ \5 D E F6 /7 G
Put the four lines inside the while in order so the level-order walk prints 1 2 3 4 5 6. The tree is the one from the first picture.
if (x->right) q[tail++] = x->right;Node *x = q[head++];if (x->left) q[tail++] = x->left;printf("%d ", x->val);
1 2 3 4 5 6
x off the queue before you can visit it or queue its children; the left child has to join before the right one, so each level comes out left to right. Visiting before or after queueing the children doesn't matter: the output is the same.This step's queue walks a full binary tree with 4 levels (15 nodes) in level order. What is the most nodes the queue holds at once?
How many nodes on each level
✓Building on level order, print how many nodes each level has. The trick: at the start of each round, the queue holds exactly one whole level, so note tail - head first.
1 2 3 1
1#include <stdio.h>2#include <stdlib.h>3 4typedef struct Node {5 int val;6 struct Node *left, *right;7} Node;8 9Node *node(int v, Node *l, Node *r) {10 Node *n = malloc(sizeof(Node));11 n->val = v; n->left = l; n->right = r;12 return n;13}14 15void widths(Node *t) {16 Node *q[100];17 int head = 0, tail = 0;18 q[tail++] = t;19 while (head < tail) {20 int k = tail - head; // this level has k21 printf("%d ", k);22 // take those k out, and put their children in23 }24 printf("\n");25}26 27int main(void) {28 Node *t = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)),29 node(3, NULL, node(6, node(7, NULL, NULL), NULL)));30 widths(t);31 return 0;32}
Summary
Four traversals: where the root goes, or level by level
- Preorder root-left-right, inorder left-root-right, postorder left-right-root: only the printf moves
- Expression trees: preorder = prefix, inorder = infix (needs brackets), postorder = postfix
- Level order: a queue, one out, its children in
- All O(n); the first in preorder and the last in postorder is the root
1void in(Node *t) {2 if (!t) return;3 in(t->left);4 printf("%d ", t->val);5 in(t->right);6}