Example 1 — Inorder on a general tree and a BST
Only the BST gives sorted output.
#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 inorder(const struct T *t) {
if (!t) return;
inorder(t->left);
printf(" %d", t->key);
inorder(t->right);
}
int main(void) {
struct T *tree = mk(1, mk(2, mk(4, NULL, NULL), mk(5, NULL, NULL)), mk(3, NULL, NULL));
struct T *bst = mk(4,
mk(2, mk(1, NULL, NULL), mk(3, NULL, NULL)),
mk(6, mk(5, NULL, NULL), mk(7, NULL, NULL)));
printf("binary tree:");
inorder(tree);
printf("\nBST:");
inorder(bst);
printf("\n");
free_tree(tree);
free_tree(bst);
return 0;
} How It Works
- For the first tree, the left subtree (4, 2, 5) is printed, then the root 1, then 3.
- The BST keeps smaller keys left, so the walk is sorted.
- If inorder is not sorted, the tree is not a valid BST.
