Example 1 — Measure leaves, height, and depth
The tree has root 1, children 2 and 3, and leaves 4 and 5 under 2.
#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 int leaves(const struct T *t) {
if (!t) return 0;
if (!t->left && !t->right) return 1;
return leaves(t->left) + leaves(t->right);
}
static int height(const struct T *t) {
if (!t) return -1;
int a = height(t->left), b = height(t->right);
return 1 + (a > b ? a : b);
}
static int depth(const struct T *t, int key, int d) {
if (!t) return -1;
if (t->key == key) return d;
int x = depth(t->left, key, d + 1);
return x >= 0 ? x : depth(t->right, key, d + 1);
}
int main(void) {
struct T *root = mk(1, mk(2, mk(4, NULL, NULL), mk(5, NULL, NULL)), mk(3, NULL, NULL));
printf("leaves: %d\n", leaves(root));
printf("height (edges): %d\n", height(root));
printf("depth of node 5: %d\n", depth(root, 5, 0));
free_tree(root);
return 0;
} How It Works
- Leaves are 4, 5, and 3.
- An empty tree has height -1 so a single node has height 0.
- Node 5 is two edges below the root (1 to 2 to 5).
