Back to Blog

C in 100 Seconds: Binary Tree Traversal

Daryl WongDaryl Wong

Video: C in 100 Seconds: Binary Tree Traversal — Inorder, Preorder, Postorder | Episode 51 by Taught by Celeste AI - AI Coding Coach

Watch full page →

Binary Tree Traversal — Inorder, Preorder, Postorder

Three ways to visit every node in a binary tree. The only difference is where the print happens relative to the recursive calls.

Inorder — Left, Root, Right

void inorder(Node *root) {
  if (root == NULL) return;
  inorder(root->left);
  printf("%d ", root->data);
  inorder(root->right);
}

Visit the left subtree, print the current node, visit the right subtree. For a BST, this gives sorted output: 20 30 40 50 60 70

Preorder — Root, Left, Right

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

Print the current node first, then visit children. Useful for copying or serializing a tree: 50 30 20 40 70 60

Postorder — Left, Right, Root

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

Visit both children before printing the current node. Useful for deleting or freeing a tree: 20 40 30 60 70 50

The Pattern

All three traversals use the same recursive structure. The only difference is where printf sits — in the middle (inorder), at the top (preorder), or at the bottom (postorder).

Student Code

Try it yourself: episode51/traversal.c