Reading history

Binary Tree in C: Traversals, Height and Level Order

6 min read 0 views

Learn binary trees in C: nodes and pointers, preorder, inorder and postorder traversal, level-order with a queue, height and node count.

Arrays, linked lists, stacks and queues store data in a line. A tree stores it in a hierarchy, like a family tree or the folders on your computer. In a binary tree every node has at most two children, called left and right. Binary trees are the foundation for search trees, heaps, expression parsers and much more, and nearly all tree code is naturally written with recursion.

In this lesson you will learn

  • Tree terminology: root, leaf, parent, child, height
  • Building a binary tree with struct and pointers
  • Preorder, inorder and postorder traversal
  • Level-order traversal with a queue
  • Recursive height and node count

Tree Terminology

TermMeaning
RootThe top node; it has no parent
Parent / childA node directly above / below another
LeafA node with no children
SubtreeA node together with all its descendants
HeightNumber of nodes on the longest path from the root down to a leaf

Some books count height in edges instead of nodes, which gives a value one smaller. Either is fine as long as you are consistent.

Building and Traversing a Tree

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

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

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

void preorder(const struct Node *r)  { if (r) { printf("%d ", r->data); preorder(r->left); preorder(r->right); } }
void inorder(const struct Node *r)   { if (r) { inorder(r->left); printf("%d ", r->data); inorder(r->right); } }
void postorder(const struct Node *r) { if (r) { postorder(r->left); postorder(r->right); printf("%d ", r->data); } }

int height(const struct Node *r) {
    if (r == NULL) return 0;
    int lh = height(r->left), rh = height(r->right);
    return 1 + (lh > rh ? lh : rh);
}

int count_nodes(const struct Node *r) {
    return r ? 1 + count_nodes(r->left) + count_nodes(r->right) : 0;
}

void free_tree(struct Node *r) {
    if (r) { free_tree(r->left); free_tree(r->right); free(r); }
}

int main(void) {
    /*        1
            /   \
           2     3
          / \     \
         4   5     6      */
    struct Node *root = new_node(1);
    root->left = new_node(2);
    root->right = new_node(3);
    root->left->left = new_node(4);
    root->left->right = new_node(5);
    root->right->right = new_node(6);

    printf("Preorder:  "); preorder(root);  printf("\n");
    printf("Inorder:   "); inorder(root);   printf("\n");
    printf("Postorder: "); postorder(root); printf("\n");
    printf("Height: %d, nodes: %d\n", height(root), count_nodes(root));
    free_tree(root);
    return 0;
}

Output

Preorder:  1 2 4 5 3 6 
Inorder:   4 2 5 1 3 6 
Postorder: 4 5 2 6 3 1 
Height: 3, nodes: 6
  • Each node is a struct holding data and two pointers. NULL means “no child”.
  • The three depth-first traversals differ only in when the node itself is visited:
    • Preorder (node, left, right): visits the root first. Useful for copying a tree.
    • Inorder (left, node, right): in a binary search tree this gives sorted order.
    • Postorder (left, right, node): visits children before parents. Used for deleting a tree, as free_tree does.
  • height and count_nodes show the usual recursive pattern: handle the empty tree, then combine the answers from the two subtrees.
  • Every traversal visits each node once, so all of them run in O(n) time.

Level-Order Traversal

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

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

struct Node *new_node(int d) {
    struct Node *n = malloc(sizeof *n);
    if (!n) exit(1);
    n->data = d; n->left = n->right = NULL;
    return n;
}

/* Level-order (breadth-first) traversal with an array-based queue */
void level_order(struct Node *root) {
    struct Node *queue[64];
    int front = 0, back = 0;
    queue[back++] = root;
    while (front < back) {
        int level_size = back - front;      /* nodes on the current level */
        for (int i = 0; i < level_size; i++) {
            struct Node *cur = queue[front++];
            printf("%d ", cur->data);
            if (cur->left)  queue[back++] = cur->left;
            if (cur->right) queue[back++] = cur->right;
        }
        printf("\n");
    }
}

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

    printf("Level by level:\n");
    level_order(root);
    return 0;
}

Output

Level by level:
1 
2 3 
4 5 6

Level-order (breadth-first) traversal visits the tree one level at a time from top to bottom. It uses a queue: take a node from the front, print it, and add its children to the back. Counting the queue size at the start of each round lets the code print one line per level. The same idea becomes breadth-first search on graphs.

Special Kinds of Binary Tree

TypeRule
FullEvery node has 0 or 2 children
CompleteAll levels are full except possibly the last, which fills from the left (used by heaps)
PerfectAll internal nodes have 2 children and all leaves are on the same level
BalancedLeft and right heights differ by at most 1 at every node
DegenerateEvery node has one child; it behaves like a linked list

Common Mistakes

  1. Forgetting the NULL base case, which crashes on the first missing child.
  2. Not setting new children to NULL after malloc, leaving garbage pointers.
  3. Freeing a node before its children, losing access to them. Free in postorder.
  4. Using recursion on extremely deep trees, which can overflow the call stack; use an explicit stack then.

Practice Exercises

Exercise 1. Write a function that counts the leaves of a binary tree.

Show answer
int count_leaves(const struct Node *r) {
    if (r == NULL) return 0;
    if (r->left == NULL && r->right == NULL) return 1;
    return count_leaves(r->left) + count_leaves(r->right);
}

For the example tree it returns 3 (nodes 4, 5 and 6).

Exercise 2. Write mirror(), which swaps the left and right children of every node.

Show answer
void mirror(struct Node *r) {
    if (r == NULL) return;
    struct Node *t = r->left;
    r->left = r->right;
    r->right = t;
    mirror(r->left);
    mirror(r->right);
}

Frequently Asked Questions

How many nodes can a binary tree of height h have?

At most 2h − 1, when every level is full (counting height in nodes). A tree with n nodes therefore has height at least about log₂ n.

Can a binary tree be stored in an array?

Yes, especially complete trees. Put the root at index 0; the children of index i are at 2i + 1 and 2i + 2. Heaps use exactly this layout.

Summary

  • A binary tree node has data plus left and right child pointers.
  • Preorder, inorder and postorder are depth-first; level-order uses a queue.
  • Most tree algorithms are short recursive functions with a NULL base case.
  • All traversals take O(n) time.

Next: Binary Search Tree in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *