Course contentsShow
← C
Lesson 1025 of 1,21914. Data Structures in CFree lesson

In-order traversal (Sorted output)

In-order traversal (Sorted output)

What you'll learn: How to visit nodes in a Binary Search Tree so that the data is processed in perfect ascending order.

The "Left-Root-Right" rule

The magic of a Binary Search Tree (BST) is its inherent organization: smaller values are always to the left, and larger values are always to the right. To take advantage of this and print the tree's contents in order (like a sorted list), we use a recursive strategy called In-order traversal.

Think of it like exploring a mountain range from left to right. To see everything in sequence, you follow a simple three-step rule at every peak (node) you encounter:

  1. Go Left: Explore everything in the left subtree first.
  2. Visit: Process (or print) the current node’s value.
  3. Go Right: Explore everything in the right subtree last.

Because of how BSTs are structured, this "Left-Root-Right" sequence ensures you always hit the smallest available number, then the middle, then the largest.

Implementing the recursion

In C, this is most elegantly handled with a recursive function. The function calls itself deeper and deeper into the left side of the tree until it hits a NULL pointer (the "end of the road"). Only then does it print a value and start looking at the right-side branches.

#include <stdio.h>

struct Node {
    int data;
    struct Node* left;
    struct Node* right;
};

void printInOrder(struct Node* root) {
    // Base case: If the current branch is empty, stop.
    if (root == NULL) {
        return;
    }

    // 1. Traverse the left subtree
    printInOrder(root->left);

    // 2. Visit the current node
    printf("%d ", root->data);

    // 3. Traverse the right subtree
    printInOrder(root->right);
}

Why it works

Imagine a tree with 5 at the root, 3 on the left, and 7 on the right.

  • The function starts at 5, but immediately pauses to visit the left child (3).
  • At 3, it checks its own left child (which is NULL), so it finally prints 3.
  • Then it checks 3's right child (also NULL).
  • Having finished with the left side, the function returns to 5, prints it, and then moves to the right child 7.

The result is a perfectly sorted output: 3 5 7. Even with thousands of nodes, this simple recursive pattern maintains the sequence perfectly.

Key takeaway

In-order traversal follows the "Left-Root-Right" pattern to extract data from a BST in sorted, ascending order.