Example 1 — Print each level on its own line
Use the queue size at the start of each round.
#include <stdio.h>
#include <stdlib.h>
struct T {
int key;
struct T *left, *right;
};
static struct T *mk(int k, struct T *l, struct T *r) {
struct T *t = malloc(sizeof *t);
if (!t) exit(1);
t->key = k;
t->left = l;
t->right = r;
return t;
}
static void free_tree(struct T *t) {
if (!t) return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
static void level_order(const struct T *root) {
const struct T *q[32];
int head = 0, tail = 0, level = 0;
if (!root) return;
q[tail++] = root;
while (head < tail) {
int n = tail - head;
printf("level %d:", level++);
for (int i = 0; i < n; i++) {
const struct T *t = q[head++];
printf(" %d", t->key);
if (t->left) q[tail++] = t->left;
if (t->right) q[tail++] = t->right;
}
printf("\n");
}
}
int main(void) {
struct T *root = mk(1, mk(2, mk(4, NULL, NULL), mk(5, NULL, NULL)), mk(3, NULL, NULL));
level_order(root);
free_tree(root);
return 0;
} How It Works
- The queue starts with the root.
- Each round handles exactly the nodes that were queued for that level.
- Children enqueued during a round form the next level.
