Example 1 — Recursive and iterative preorder
Both versions give the same order.
#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 preorder(const struct T *t) {
if (!t) return;
printf(" %d", t->key);
preorder(t->left);
preorder(t->right);
}
static void preorder_iter(const struct T *root) {
const struct T *st[32];
int top = -1;
if (root) st[++top] = root;
while (top >= 0) {
const struct T *n = st[top--];
printf(" %d", n->key);
if (n->right) st[++top] = n->right;
if (n->left) st[++top] = n->left;
}
}
int main(void) {
struct T *root = mk(1, mk(2, mk(4, NULL, NULL), mk(5, NULL, NULL)), mk(3, NULL, NULL));
printf("recursive:");
preorder(root);
printf("\niterative:");
preorder_iter(root);
printf("\n");
free_tree(root);
return 0;
} How It Works
- The root 1 is printed first, then the whole left subtree 2, 4, 5.
- The right subtree 3 comes last.
- The iterative version pushes right before left so left pops first.
