Example 1 — Count nodes and find the height of a tree
A small hand-built binary tree.
#include <stdio.h>
struct T { int v; struct T *l, *r; };
static int count(const struct T *t) {
return t ? 1 + count(t->l) + count(t->r) : 0;
}
static int height(const struct T *t) {
if (!t) return 0;
int a = height(t->l), b = height(t->r);
return 1 + (a > b ? a : b);
}
int main(void) {
struct T n4 = {4, NULL, NULL}, n5 = {5, NULL, NULL}, n3 = {3, NULL, NULL};
struct T n2 = {2, &n4, &n5};
struct T n1 = {1, &n2, &n3};
printf("nodes: %d\n", count(&n1));
printf("height: %d\n", height(&n1));
return 0;
} How It Works
- Each node may have two children, so recursion mirrors the shape.
- The height is the number of levels, counting the root level.
- Longest path: 1 -> 2 -> 4 gives three levels.
