Example 1 — Search with comparison counts
Find 60 and fail to find 45.
#include <stdio.h>
#include <stdlib.h>
struct T {
int key;
struct T *left, *right;
};
static struct T *mk(int k) {
struct T *t = malloc(sizeof *t);
if (!t) exit(1);
t->key = k;
t->left = t->right = NULL;
return t;
}
static int insert(struct T **root, int k) {
struct T **pp = root;
while (*pp) {
if (k == (*pp)->key) return 0;
pp = k < (*pp)->key ? &(*pp)->left : &(*pp)->right;
}
*pp = mk(k);
return 1;
}
static void inorder(const struct T *t) {
if (!t) return;
inorder(t->left);
printf(" %d", t->key);
inorder(t->right);
}
static void free_tree(struct T *t) {
if (!t) return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
static int search(const struct T *t, int k, int *steps) {
*steps = 0;
while (t) {
(*steps)++;
if (k == t->key) return 1;
t = k < t->key ? t->left : t->right;
}
return 0;
}
int main(void) {
int keys[] = {50, 30, 70, 20, 40, 60, 80};
struct T *root = NULL;
for (int i = 0; i < 7; i++) insert(&root, keys[i]);
int steps;
if (search(root, 60, &steps)) printf("found 60 after %d comparisons\n", steps);
if (!search(root, 45, &steps)) printf("45 not found after %d comparisons\n", steps);
free_tree(root);
return 0;
} How It Works
- 60: 50, then 70, then 60 is found.
- 45: 50, then 30, then 40, then the right child of 40 is empty.
- Each step discards a whole subtree.
