In a binary tree each node has at most two children, named left and right. Useful shapes include a full tree (every node has 0 or 2 children), a complete tree (all levels filled except possibly the last, filled left to right), and a perfect tree (all leaves at the same depth). A perfect tree of height h has 2^(h+1) - 1 nodes.
Remember
struct T {
int key;
struct T *left, *right;
};
Reference
Cheat Sheet
Keep these facts handy while you work with Binary Trees in C.
#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 is_full(const struct T *t) {
if (!t) return 1;
if (!t->left && !t->right) return 1;
if (t->left && t->right) return is_full(t->left) && is_full(t->right);
return 0;
}
int main(void) {
struct T *a = mk(1, mk(2, mk(4, NULL, NULL), mk(5, NULL, NULL)), mk(3, NULL, NULL));
struct T *b = mk(1, mk(2, NULL, NULL), NULL);
printf("tree A full: %s\n", is_full(a) ? "yes" : "no");
printf("tree B full: %s\n", is_full(b) ? "yes" : "no");
free_tree(a);
free_tree(b);
return 0;
}
Output
tree A full: yes
tree B full: no
How It Works
Every node of tree A has either zero or two children.
Tree B's root has only a left child.
The check recurses into both subtrees only when both exist.
Edge Cases & Pitfalls
Check these before relying on Binary Trees in real programs.
mix
Confusing full and complete
Full is about child counts; complete is about level filling.
null
Checking only one child
t->left->key crashes when left is NULL.
Remember
Key Takeaways
At most two children.
Full, complete, perfect are different.
Recurse on both sides.
One line: In a binary tree each node has at most two children, named left and right.
Frequently Asked Questions
A tree in which every node has at most two children, called left and right.
A full tree has nodes with either 0 or 2 children. A complete tree has all levels filled except possibly the last, which is filled from the left.
Continue with "C Binary Tree Representation" next. Represent a binary tree with linked nodes or with array index formulas. The C Trees and Binary Search Trees hub lists every topic in order.