Skip to content
StudyFame

Tree Traversal in C

A list has one natural order: front to back. A tree doesn't. You can visit the root first, last or in the middle, or go level by level. Each way is called a traversal, and each one is useful for a different job: printing a BST in sorted order, copying a tree, deleting it, or showing it level by level.

In this lesson you will learn the four standard traversals, inorder, preorder, postorder and level order, with recursive and queue-based programs, a simple trick to do them by hand in exams, and how an expression tree gives prefix, infix and postfix notation.

What You Will Learn

  • What tree traversal means.
  • Depth-first traversals: inorder, preorder, postorder.
  • Breadth-first traversal: level order using a queue.
  • How to write each traversal in C.
  • A quick hand method for exam questions.
  • Uses of each traversal, including expression trees.

Tree Traversal in C Explained

Exam definition: Tree traversal is the process of visiting every node of a tree exactly once in a systematic order. In depth-first traversals of a binary tree: preorder visits Node–Left–Right, inorder visits Left–Node–Right, and postorder visits Left–Right–Node. Level order (breadth-first) traversal visits nodes level by level from left to right, using a queue. Each traversal takes O(n) time.

Memory trick: The name tells you where the Node goes. Pre = node before children (N L R). In = node in between (L N R). Post = node after children (L R N). Left always comes before Right.

              1
            /   \
           2     3
          / \   / \
         4   5 6   7

Preorder   (N L R): 1 2 4 5 3 6 7
Inorder    (L N R): 4 2 5 1 6 3 7
Postorder  (L R N): 4 5 2 6 7 3 1
Level order       : 1 2 3 4 5 6 7

Syntax: The Three Recursive Traversals

void preorder(struct tnode *t)  { if (t) { visit(t); preorder(t->left);  preorder(t->right);  } }
void inorder(struct tnode *t)   { if (t) { inorder(t->left);  visit(t);  inorder(t->right);   } }
void postorder(struct tnode *t) { if (t) { postorder(t->left); postorder(t->right); visit(t); } }
TraversalOrderTypical use
PreorderNode, Left, RightCopying a tree, prefix expression, saving a tree to a file
InorderLeft, Node, RightSorted output of a BST, infix expression
PostorderLeft, Right, NodeDeleting/freeing a tree, postfix expression, folder sizes
Level orderLevel by levelPrinting by levels, shortest path in unweighted trees, BFS

Example 1: All Four Traversals

#include <stdio.h>
#include <stdlib.h>

struct tnode
{
    int data;
    struct tnode *left, *right;
};

struct tnode *node(int v)
{
    struct tnode *n = malloc(sizeof *n);
    if (n == NULL)
        exit(1);
    n->data = v;
    n->left = n->right = NULL;
    return n;
}

void preorder(const struct tnode *t)
{
    if (t == NULL) return;
    printf("%d ", t->data);
    preorder(t->left);
    preorder(t->right);
}

void inorder(const struct tnode *t)
{
    if (t == NULL) return;
    inorder(t->left);
    printf("%d ", t->data);
    inorder(t->right);
}

void postorder(const struct tnode *t)
{
    if (t == NULL) return;
    postorder(t->left);
    postorder(t->right);
    printf("%d ", t->data);
}

void level_order(const struct tnode *root)
{
    const struct tnode *queue[100];          /* simple array queue of pointers */
    int front = 0, rear = 0;
    const struct tnode *t;

    if (root == NULL) return;
    queue[rear++] = root;
    while (front < rear)
    {
        t = queue[front++];                  /* dequeue */
        printf("%d ", t->data);
        if (t->left)  queue[rear++] = t->left;   /* enqueue children */
        if (t->right) queue[rear++] = t->right;
    }
}

void free_tree(struct tnode *t)                /* postorder free */
{
    if (t == NULL) return;
    free_tree(t->left);
    free_tree(t->right);
    free(t);
}

int main(void)
{
    struct tnode *root = node(1);
    root->left = node(2);
    root->right = node(3);
    root->left->left = node(4);
    root->left->right = node(5);
    root->right->left = node(6);
    root->right->right = node(7);

    printf("Preorder   : "); preorder(root);    printf("\n");
    printf("Inorder    : "); inorder(root);     printf("\n");
    printf("Postorder  : "); postorder(root);   printf("\n");
    printf("Level order: "); level_order(root); printf("\n");

    free_tree(root);
    return 0;
}

Output

Preorder   : 1 2 4 5 3 6 7
Inorder    : 4 2 5 1 6 3 7
Postorder  : 4 5 2 6 7 3 1
Level order: 1 2 3 4 5 6 7 

Code Explanation

  1. The three depth-first functions are identical except for where the printf sits: before, between or after the two recursive calls.
  2. Preorder prints 1, then the whole left subtree (2 4 5), then the right subtree (3 6 7).
  3. Inorder goes as far left as possible first (4), then its parent (2), then 2's right (5), then the root (1), and so on.
  4. Postorder prints a node only after both of its subtrees, so the root 1 comes last. That's why free_tree uses postorder: children are freed before their parent.
  5. level_order uses a queue: dequeue a node, print it, enqueue its children. Because a queue is FIFO, all nodes of one level come out before the next level.

How to Find Traversals by Hand (Exam Trick)

Draw a line around the tree, starting left of the root and going counter-clockwise (down the left side first). Each node is touched up to three times:

Preorder : write a node when you pass its LEFT side   (first touch)
Inorder  : write a node when you pass UNDER it        (second touch)
Postorder: write a node when you pass its RIGHT side  (last touch)

Another check: in preorder the root is first, in postorder the root is last, and in inorder the root splits the left and right subtrees. Given preorder (or postorder) plus inorder, you can rebuild the whole tree, a common exam question.

Example 2: Expression Tree (Prefix, Infix, Postfix)

#include <stdio.h>
#include <stdlib.h>

/* A node is an operator (+ - * /) or a number */
struct enode
{
    char op;                 /* 0 for a number */
    int value;
    struct enode *left, *right;
};

struct enode *num(int v)
{
    struct enode *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->op = 0; n->value = v; n->left = n->right = NULL;
    return n;
}

struct enode *opr(char op, struct enode *l, struct enode *r)
{
    struct enode *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->op = op; n->value = 0; n->left = l; n->right = r;
    return n;
}

void show(const struct enode *t)
{
    if (t->op) printf("%c ", t->op); else printf("%d ", t->value);
}

void prefix(const struct enode *t)  { if (t) { show(t); prefix(t->left); prefix(t->right); } }
void postfix(const struct enode *t) { if (t) { postfix(t->left); postfix(t->right); show(t); } }

void infix(const struct enode *t)
{
    if (t == NULL) return;
    if (t->op) printf("( ");
    infix(t->left);
    show(t);
    infix(t->right);
    if (t->op) printf(") ");
}

int evaluate(const struct enode *t)          /* postorder: children first */
{
    int a, b;
    if (t->op == 0) return t->value;
    a = evaluate(t->left);
    b = evaluate(t->right);
    switch (t->op)
    {
    case '+': return a + b;
    case '-': return a - b;
    case '*': return a * b;
    default : return a / b;
    }
}

void free_tree(struct enode *t)
{
    if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}

int main(void)
{
    /* (3 + 4) * (5 - 2)  */
    struct enode *root = opr('*', opr('+', num(3), num(4)), opr('-', num(5), num(2)));

    printf("Prefix  : "); prefix(root);  printf("\n");
    printf("Infix   : "); infix(root);   printf("\n");
    printf("Postfix : "); postfix(root); printf("\n");
    printf("Value   : %d\n", evaluate(root));
    free_tree(root);
    return 0;
}

Output

Prefix  : * + 3 4 - 5 2
Infix   : ( ( 3 + 4 ) * ( 5 - 2 ) )
Postfix : 3 4 + 5 2 - *
Value   : 21
  • In an expression tree, leaves are numbers and internal nodes are operators.
  • Preorder gives prefix (Polish) notation, inorder gives infix (with brackets added), postorder gives postfix (Reverse Polish) notation.
  • evaluate is a postorder traversal: it computes both operands before applying the operator: (3 + 4) × (5 − 2) = 7 × 3 = 21. Compilers and calculators work this way.

Important Points to Remember

  • Preorder = N L R; Inorder = L N R; Postorder = L R N.
  • Level order = breadth-first, using a queue.
  • Every traversal is O(n): each node is visited once.
  • Inorder of a BST = sorted order.
  • Postorder is used to free a tree and to evaluate expressions.
  • Preorder or postorder together with inorder uniquely identifies a binary tree.

Common Mistakes Beginners Make

MistakeWhat happensFix
Visiting right before leftOrder differs from the standard answerLeft always comes before right
Missing the NULL base caseCrash on leaves' childrenif (t == NULL) return;
Using a stack for level orderGives a depth-first order insteadLevel order needs a queue
Freeing the tree in preorderChildren are read after the parent is freedFree in postorder
Fixed-size queue too small for a big treeArray overflowSize it for the number of nodes, or use a linked queue

Tree Traversal Practice Questions

  1. Define preorder, inorder and postorder traversal.
  2. Which data structure is used for level-order traversal, and why?
  3. Write all three traversals of a tree with root A, left child B (children D, E) and right child C.
  4. Which traversal is used to delete a tree? Why?
  5. Which traversal of an expression tree gives postfix notation?
Show answers
  1. Preorder: node, left, right. Inorder: left, node, right. Postorder: left, right, node.
  2. A queue, because FIFO order makes all nodes of a level come out before the nodes of the next level.
  3. Preorder: A B D E C. Inorder: D B E A C. Postorder: D E B C A.
  4. Postorder, because both children are deleted before their parent, so no freed node is accessed.
  5. Postorder.

Coding Exercise

Modify level-order traversal to print each level on its own line, like "Level 0: 1", "Level 1: 2 3". Test it on the tree from Example 1. Hint: before processing a level, note how many nodes are in the queue.

Show solution
#include <stdio.h>
#include <stdlib.h>

struct tnode
{
    int data;
    struct tnode *left, *right;
};

struct tnode *node(int v)
{
    struct tnode *n = malloc(sizeof *n);
    if (n == NULL) exit(1);
    n->data = v;
    n->left = n->right = NULL;
    return n;
}

void print_levels(const struct tnode *root)
{
    const struct tnode *queue[100], *t;
    int front = 0, rear = 0, level = 0, count, i;

    if (root == NULL) return;
    queue[rear++] = root;
    while (front < rear)
    {
        count = rear - front;              /* nodes in this level */
        printf("Level %d:", level++);
        for (i = 0; i < count; i++)
        {
            t = queue[front++];
            printf(" %d", t->data);
            if (t->left)  queue[rear++] = t->left;
            if (t->right) queue[rear++] = t->right;
        }
        printf("\n");
    }
}

void free_tree(struct tnode *t)
{
    if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}

int main(void)
{
    struct tnode *root = node(1);
    root->left = node(2);
    root->right = node(3);
    root->left->left = node(4);
    root->left->right = node(5);
    root->right->left = node(6);
    root->right->right = node(7);

    print_levels(root);
    free_tree(root);
    return 0;
}
Level 0: 1
Level 1: 2 3
Level 2: 4 5 6 7

Quick Quiz: Tree Traversal (MCQ)

  1. Inorder traversal visits nodes in the order:

    A) N L R   B) L N R   C) L R N   D) R N L

  2. In which traversal is the root always visited last?

    A) Preorder   B) Inorder   C) Postorder   D) Level order

  3. Level-order traversal uses a:

    A) Stack   B) Queue   C) Heap   D) Hash table

  4. Preorder of an expression tree gives:

    A) Infix   B) Prefix   C) Postfix   D) Sorted order

  5. The time complexity of any traversal of n nodes is:

    A) O(1)   B) O(log n)   C) O(n)   D) O(n²)

Show answers
  1. B: L N R.
  2. C: postorder.
  3. B: a queue.
  4. B: prefix.
  5. C: O(n).

Quick Revision for Exams and Interviews

Read this before your exam. The highlighted words are the answer.

Must-remember facts

PreorderN L R: root first
InorderL N R: BST gives sorted order
PostorderL R N: root last, used to free
Level orderBreadth-first with a queue
TimeO(n) for each
Expression treePre → prefix, In → infix, Post → postfix
Rebuild a treeInorder + preorder (or postorder)

Frequently asked questions

What are the types of tree traversal?
Depth-first: preorder, inorder, postorder; and breadth-first: level order.
What is the difference between inorder and preorder?
Preorder visits the node before its subtrees; inorder visits it between the left and right subtrees.
How is level-order traversal done?
Put the root in a queue; repeatedly dequeue a node, visit it and enqueue its children.

Remember

  • The name says where the Node goes: pre, in, post.
  • Depth-first = recursion (stack); breadth-first = queue.

Next Topic

Next lesson: Graphs, BFS and DFS in C. You will represent a graph with an adjacency matrix and explore it with BFS and DFS.