Skip to content
Laviyx Learn

Try

DS Lab · Experiment 11

Binary tree traversals, recursive and non-recursive

CTreesJNTUH R22 · CS306PC

Aim

To write a C program that builds a binary tree (by binary search tree insertion of the given values) and prints its inorder, preorder and postorder traversals both recursively and non-recursively (using an explicit stack), and also its level order traversal.

Algorithm

  1. Read n values and insert them one by one into a binary search tree to build the tree.
  2. Recursive traversals: inorder visits left subtree, root, right subtree; preorder visits root, left, right; postorder visits left, right, root.
  3. Non-recursive inorder: start at the root. Push nodes while moving left. When you reach NULL, pop a node, print it, and move to its right child. Stop when the node is NULL and the stack is empty.
  4. Non-recursive preorder: push the root. While the stack is not empty, pop a node, print it, then push its right child and then its left child (so the left one is popped first).
  5. Non-recursive postorder (two stacks): push the root on stack 1. While stack 1 is not empty, pop a node, push it on stack 2, and push its left and then right child on stack 1. Finally pop and print everything from stack 2.
  6. Level order: put the root in a queue. While the queue is not empty, remove a node, print it, and add its left and right children.
  7. Free all nodes.

Program

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

#define MAX 50

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

struct node *new_node(int value) {
    struct node *n = malloc(sizeof(struct node));
    if (n == NULL) {
        printf("Memory not available\n");
        exit(1);
    }
    n->data = value;
    n->left = n->right = NULL;
    return n;
}

struct node *insert(struct node *root, int value) {
    if (root == NULL) {
        return new_node(value);
    }
    if (value < root->data) {
        root->left = insert(root->left, value);
    } else if (value > root->data) {
        root->right = insert(root->right, value);
    } else {
        printf("%d is a duplicate, skipped\n", value);
    }
    return root;
}

/* ---------- recursive traversals ---------- */
void inorder(struct node *root) {
    if (root != NULL) {
        inorder(root->left);
        printf("%d ", root->data);
        inorder(root->right);
    }
}

void preorder(struct node *root) {
    if (root != NULL) {
        printf("%d ", root->data);
        preorder(root->left);
        preorder(root->right);
    }
}

void postorder(struct node *root) {
    if (root != NULL) {
        postorder(root->left);
        postorder(root->right);
        printf("%d ", root->data);
    }
}

/* ---------- non-recursive traversals (explicit stack) ---------- */
void inorder_iterative(struct node *root) {
    struct node *stack[MAX];
    int top = -1;
    struct node *curr = root;
    while (curr != NULL || top != -1) {
        while (curr != NULL) {          /* go as far left as possible */
            stack[++top] = curr;
            curr = curr->left;
        }
        curr = stack[top--];
        printf("%d ", curr->data);
        curr = curr->right;
    }
}

void preorder_iterative(struct node *root) {
    struct node *stack[MAX];
    int top = -1;
    if (root == NULL) {
        return;
    }
    stack[++top] = root;
    while (top != -1) {
        struct node *curr = stack[top--];
        printf("%d ", curr->data);
        if (curr->right != NULL) {      /* right first, so left is popped first */
            stack[++top] = curr->right;
        }
        if (curr->left != NULL) {
            stack[++top] = curr->left;
        }
    }
}

void postorder_iterative(struct node *root) {
    struct node *stack1[MAX], *stack2[MAX];
    int top1 = -1, top2 = -1;
    if (root == NULL) {
        return;
    }
    stack1[++top1] = root;
    while (top1 != -1) {
        struct node *curr = stack1[top1--];
        stack2[++top2] = curr;          /* stack2 collects root, right, left */
        if (curr->left != NULL) {
            stack1[++top1] = curr->left;
        }
        if (curr->right != NULL) {
            stack1[++top1] = curr->right;
        }
    }
    while (top2 != -1) {                /* popping reverses it: left, right, root */
        printf("%d ", stack2[top2--]->data);
    }
}

void level_order(struct node *root) {
    struct node *queue[MAX];
    int front = 0, rear = 0;
    if (root == NULL) {
        return;
    }
    queue[rear++] = root;
    while (front < rear) {
        struct node *curr = queue[front++];
        printf("%d ", curr->data);
        if (curr->left != NULL) {
            queue[rear++] = curr->left;
        }
        if (curr->right != NULL) {
            queue[rear++] = curr->right;
        }
    }
}

void free_tree(struct node *root) {
    if (root != NULL) {
        free_tree(root->left);
        free_tree(root->right);
        free(root);
    }
}

int main(void) {
    struct node *root = NULL;
    int n, value;

    printf("Enter number of nodes (1-%d): ", MAX);
    if (scanf("%d", &n) != 1 || n < 1 || n > MAX) {
        printf("Invalid number of nodes\n");
        return 1;
    }
    printf("Enter %d values: ", n);
    for (int i = 0; i < n; i++) {
        if (scanf("%d", &value) != 1) {
            printf("Invalid input\n");
            free_tree(root);
            return 1;
        }
        root = insert(root, value);
    }

    printf("\nInorder   (recursive)    : ");
    inorder(root);
    printf("\nInorder   (non-recursive): ");
    inorder_iterative(root);
    printf("\n\nPreorder  (recursive)    : ");
    preorder(root);
    printf("\nPreorder  (non-recursive): ");
    preorder_iterative(root);
    printf("\n\nPostorder (recursive)    : ");
    postorder(root);
    printf("\nPostorder (non-recursive): ");
    postorder_iterative(root);
    printf("\n\nLevel order              : ");
    level_order(root);
    printf("\n");

    free_tree(root);
    return 0;
}

Output

Output
Enter number of nodes (1-50): 8
Enter 8 values: 50 30 70 20 40 60 80 45

Inorder   (recursive)    : 20 30 40 45 50 60 70 80 
Inorder   (non-recursive): 20 30 40 45 50 60 70 80 

Preorder  (recursive)    : 50 30 20 40 45 70 60 80 
Preorder  (non-recursive): 50 30 20 40 45 70 60 80 

Postorder (recursive)    : 20 45 40 30 60 80 70 50 
Postorder (non-recursive): 20 45 40 30 60 80 70 50 

Level order              : 50 30 70 20 40 60 80 45 

Recorded by compiling and running this exact program. Typed input appears after each prompt.

How it works

The values 50 30 70 20 40 60 80 45 build this tree (45 is the right child of 40):

Text
          50
        /    \
      30      70
     /  \    /  \
   20   40  60   80
          \
          45

Each recursive and non-recursive pair prints the same order, which is the check that the stack versions are right. The stacks and the queue are arrays of size MAX, which is enough because the tree has at most MAX nodes.

The syllabus does not say how to build the tree, so the program uses binary search tree insertion. The traversal functions work the same way for any binary tree.

Common mistakes

  • In iterative preorder, pushing the left child before the right child. The stack is last in, first out, so the right subtree would be printed first.

  • Writing the inorder loop condition as only while (top != -1). At the start the stack is empty while curr is the root, so nothing is printed. The condition must be curr != NULL || top != -1.

  • Forgetting the base case if (root != NULL) in the recursive functions, which dereferences NULL and crashes.

  • Mixing up the order: in preorder the root comes first, in inorder in the middle, and in postorder last.

Viva questions

Try to answer each one aloud before you open it.

  • What are the three depth-first traversals of a binary tree?

    Inorder (left, root, right), preorder (root, left, right) and postorder (left, right, root).

  • What is special about the inorder traversal of a binary search tree?

    It prints the values in ascending sorted order, because every left subtree holds smaller values and every right subtree larger ones.

  • Why do the non-recursive versions need a stack?

    Recursion remembers the nodes we still have to come back to on the call stack. Without recursion we must keep those nodes ourselves, and a stack gives them back in the same last-in, first-out order.

  • Which data structure does level order traversal use?

    A queue. Nodes are visited level by level from left to right, which is breadth-first order.

  • Can a binary tree be rebuilt from its traversals?

    Yes, from its inorder together with either its preorder or its postorder traversal. Preorder and postorder alone are not enough in general.

  • What is the time complexity of each traversal?

    O(n), because every node is visited exactly once.

Learn the concepts

All Data Structures Lab experiments →