Kodewick
Start learning →
The four traversals of a binary tree21 / 50

The four traversals of a binary tree

Lesson 21 of 50 · Part 5 · Trees · about 16 minutes

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.

1
2
4
5
3
6

Preorder: visit a node as soon as you reach it (the number at its top right is its turn), then go left, and right only once the left is done

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).

Choose one

Write down this tree's preorder traversal.

1        A2       / \3      B   C4     / \   \5    D   E   F6           /7          G
Choose one

Same tree: write down its inorder traversal.

1        A2       / \3      B   C4     / \   \5    D   E   F6           /7          G
Choose one

Write down this tree's postorder traversal.

1          A2        /   \3       B     C4        \   /5         D E6        /7       F
Fill inTap one to fill a blank; tap a blank to take it back

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}
Exercise 1

Write postorder

Finish post: left, right, and print this node last.

It should print
1 6 3 14 10 8
exercise1.c
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}
Output
Press Run or Ctrl+Enter

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.

*
+
3
4
5

Postorder on an expression tree: left, right, then the node itself, which reads out the postfix expression 3 4 + 5 *
main.c
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}
Output
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.

Guess the outputA wrong guess is fine

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}
Choose one

What is this expression tree's postorder traversal (its postfix expression)?

1      *2     / \3    3   +4       / \5      4   5
Choose one

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.)

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
2
4
5
3
6

Level order: take one off the queue, visit it, and put its children at the back
main.c
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}
Output
1 2 3 4 5 6 
TraversalOrderHowThis tree
Preorderroot left rightrecursion, visit first1 2 4 5 3 6
Inorderleft root rightrecursion, visit in between4 2 5 1 3 6
Postorderleft right rootrecursion, visit last4 5 2 6 3 1
Level orderlevel by levela queue1 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.

Choose one

Write down this tree's level-order traversal.

1        A2       / \3      B   C4     / \   \5    D   E   F6           /7          G
Put in orderDrag, or use the arrows

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.

  1. if (x->right) q[tail++] = x->right;
  2. Node *x = q[head++];
  3. if (x->left) q[tail++] = x->left;
  4. printf("%d ", x->val);
Should print
1 2 3 4 5 6
Choose one

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?

Exercise 2

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.

It should print
1 2 3 1
exercise2.c
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}
Output
Press Run or Ctrl+Enter

Summary

Take-away

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}