Binary Tree in C
All the structures so far (arrays, lists, stacks, queues) were linear: one item after another. A tree is non-linear: one item can lead to several others, like folders inside folders on your computer. The most common tree in programming is the binary tree, where each node has at most two children.
In this lesson you will learn binary tree terms (root, parent, child, leaf, height, level), the types of binary trees, how to create a tree in C with pointers, and recursive functions to count nodes, count leaves and find the height. You will also see how a tree can be stored in an array.
What You Will Learn
- What a tree and a binary tree are.
- Tree terminology: root, parent, child, sibling, leaf, level, height, depth.
- Types: full, complete, perfect and skewed binary trees.
- How to represent and create a binary tree node in C.
- Recursive functions for node count, leaf count and height.
- The array representation of a binary tree.
Binary Tree in C Explained
Exam definition: A tree is a non-linear data structure consisting of nodes connected by edges, with one special node called the root and no cycles. A binary tree is a tree in which every node has at most two children, called the left child and the right child. In C, a binary tree node is a structure containing the data and two pointers, left and right; a missing child is represented by NULL.
Memory trick: A binary tree is a family tree where every parent has at most two children. The great-grandparent at the top is the root; people with no children are leaves; brothers and sisters are siblings; and the number of generations from top to bottom is the height. (Programmers draw trees upside down: root at the top!)
A <- root (level 0)
/ \
B C <- level 1 (B and C are siblings)
/ \ \
D E F <- level 2 (D, E, F are leaves)
Parent of E = B Children of B = D, E Height = 2 (edges on the longest path)
Tree terminology
| Term | Meaning | In the tree above |
|---|---|---|
| Root | Top node with no parent | A |
| Parent / child | A node and the nodes directly below it | B is the parent of D and E |
| Siblings | Children of the same parent | B and C; D and E |
| Leaf | Node with no children | D, E, F |
| Internal node | Node with at least one child | A, B, C |
| Degree | Number of children of a node | deg(B) = 2, deg(C) = 1 |
| Level / depth | Number of edges from the root | A = 0, B = 1, D = 2 |
| Height of tree | Edges on the longest root-to-leaf path | 2 |
Note: some books count height in nodes (then this tree's height is 3). Follow your textbook; this tutorial counts edges, and an empty tree has height −1.
Syntax: A Binary Tree Node in C
struct tnode
{
int data;
struct tnode *left; /* left child (NULL if none) */
struct tnode *right; /* right child (NULL if none) */
};
struct tnode *root = NULL; /* empty tree */
Types of binary trees
| Type | Rule |
|---|---|
| Full (strict) binary tree | Every node has 0 or 2 children |
| Complete binary tree | All levels full except possibly the last, which is filled from the left |
| Perfect binary tree | All internal nodes have 2 children and all leaves are on the same level; height h has 2h+1 − 1 nodes |
| Skewed binary tree | Every node has only a left (or only a right) child, like a linked list |
| Binary search tree | Left subtree < node < right subtree (next lesson) |
Example 1: Create a Binary Tree and Find Its Properties
#include <stdio.h>
#include <stdlib.h>
struct tnode
{
int data;
struct tnode *left, *right;
};
struct tnode *new_node(int value)
{
struct tnode *n = malloc(sizeof *n);
if (n == NULL)
exit(1);
n->data = value;
n->left = n->right = NULL;
return n;
}
int count_nodes(const struct tnode *t)
{
if (t == NULL)
return 0;
return 1 + count_nodes(t->left) + count_nodes(t->right);
}
int count_leaves(const struct tnode *t)
{
if (t == NULL)
return 0;
if (t->left == NULL && t->right == NULL)
return 1;
return count_leaves(t->left) + count_leaves(t->right);
}
int height(const struct tnode *t)
{
int hl, hr;
if (t == NULL)
return -1; /* empty tree */
hl = height(t->left);
hr = height(t->right);
return 1 + (hl > hr ? hl : hr);
}
int sum(const struct tnode *t)
{
return t == NULL ? 0 : t->data + sum(t->left) + sum(t->right);
}
void preorder(const struct tnode *t)
{
if (t == NULL)
return;
printf("%d ", t->data);
preorder(t->left);
preorder(t->right);
}
void free_tree(struct tnode *t)
{
if (t == NULL)
return;
free_tree(t->left);
free_tree(t->right);
free(t);
}
int main(void)
{
/* 1
/ \
2 3
/ \ \
4 5 6
/
7 */
struct tnode *root = new_node(1);
root->left = new_node(2);
root->right = new_node(3);
root->left->left = new_node(4);
root->left->right = new_node(5);
root->right->right = new_node(6);
root->right->right->left = new_node(7);
printf("Preorder : ");
preorder(root);
printf("\nNodes : %d\n", count_nodes(root));
printf("Leaves : %d\n", count_leaves(root));
printf("Height : %d\n", height(root));
printf("Sum : %d\n", sum(root));
free_tree(root);
return 0;
}
Output
Preorder : 1 2 4 5 3 6 7 Nodes : 7 Leaves : 3 Height : 3 Sum : 28
Code Explanation
new_nodecreates a node with no children (left = right = NULL). We then link children by assigning toleftandright.- Almost every tree function is recursive: solve the problem for the left subtree and the right subtree, then combine with the current node. The base case is an empty tree (
NULL). count_nodes= 1 (this node) + nodes on the left + nodes on the right = 7.count_leavesreturns 1 for a node with no children: 4, 5 and 7, so 3 leaves.height= 1 + the larger of the two subtree heights. The longest path is 1 → 3 → 6 → 7, which has 3 edges.free_treefrees the children before the parent (postorder), so no pointer is used after it is freed.
How Recursion Works on a Tree
Here is how count_nodes handles the subtree rooted at 2:
count(2) = 1 + count(4) + count(5)
= 1 + (1 + count(NULL) + count(NULL)) + (1 + count(NULL) + count(NULL))
= 1 + (1 + 0 + 0) + (1 + 0 + 0)
= 3
Each function call handles one node and trusts the recursive calls for its subtrees. That is why tree code is short. The cost is O(n): every node is visited once.
Array representation of a binary tree
A complete binary tree can be stored in an array without pointers. For the node at index i (starting at 0):
left child = 2*i + 1
right child = 2*i + 2
parent = (i - 1) / 2
10 index: 0 1 2 3 4 5
/ \ 10 20 30 40 50 60
20 30
/ \ /
40 50 60
This is how heaps (used in heap sort and priority queues) are stored.
Example 2: Binary Tree Stored in an Array
#include <stdio.h>
#define N 7
int tree[N] = {10, 20, 30, 40, 50, 60, 70};
void print_family(int i)
{
int l = 2 * i + 1, r = 2 * i + 2;
printf("%d: ", tree[i]);
if (i > 0)
printf("parent=%d ", tree[(i - 1) / 2]);
else
printf("root ");
if (l < N) printf("left=%d ", tree[l]);
if (r < N) printf("right=%d", tree[r]);
if (l >= N) printf("(leaf)");
printf("\n");
}
void inorder(int i)
{
if (i >= N)
return;
inorder(2 * i + 1);
printf("%d ", tree[i]);
inorder(2 * i + 2);
}
int main(void)
{
int i;
for (i = 0; i < N; i++)
print_family(i);
printf("Inorder: ");
inorder(0);
printf("\n");
return 0;
}
Output
10: root left=20 right=30 20: parent=10 left=40 right=50 30: parent=10 left=60 right=70 40: parent=20 (leaf) 50: parent=20 (leaf) 60: parent=30 (leaf) 70: parent=30 (leaf) Inorder: 40 20 50 10 60 30 70
- No pointers are needed: the position in the array tells you where the children and parent are.
- This tree is perfect (height 2, 23 − 1 = 7 nodes), so no array slot is wasted.
- For trees with many missing children (for example, skewed trees), the array wastes a lot of space; pointers are better.
Important Points to Remember
- A binary tree node has data, left and right; a missing child is NULL.
- Root has no parent; a leaf has no children.
- Height = edges on the longest root-to-leaf path (empty tree = −1 in this tutorial).
- Tree algorithms are naturally recursive: base case = NULL.
- Maximum nodes at level L = 2L; a perfect tree of height h has 2h+1 − 1 nodes.
- Array form: children at 2i+1 and 2i+2, parent at (i−1)/2.
Common Mistakes Beginners Make
| Mistake | What happens | Fix |
|---|---|---|
Forgetting left = right = NULL in a new node | Recursion follows garbage pointers and crashes | Always set both children to NULL |
No base case if (t == NULL) | Infinite recursion / crash | Handle the empty tree first |
| Freeing the parent before its children | Children become unreachable (leak) or are read after free | Free in postorder: left, right, then node |
| Mixing "height in edges" and "height in nodes" | Answers off by one | State which definition you use |
| Using array form for a sparse tree | Huge wasted arrays | Use linked nodes for irregular trees |
Binary Tree Practice Questions
- What is a binary tree? How is it different from a general tree?
- Define root, leaf, sibling, level and height.
- Differentiate between full, complete and perfect binary trees.
- What is the maximum number of nodes in a binary tree of height 3?
- In array representation, where are the children of the node at index 4?
Show answers
- A tree where each node has at most two children (left and right); a general tree's nodes can have any number of children.
- Root: top node; leaf: node with no children; siblings: children of the same parent; level: edges from the root; height: edges on the longest root-to-leaf path.
- Full: every node has 0 or 2 children. Complete: all levels full except the last, filled from the left. Perfect: all internal nodes have 2 children and all leaves are at the same level.
- 24 − 1 = 15.
- Left at 2×4+1 = 9, right at 2×4+2 = 10.
Coding Exercise
Write a recursive function int find_max(struct tnode *t) that returns the largest value in a binary tree (not a BST), and int count_internal(struct tnode *t) that counts nodes with at least one child. Test them on a tree with root 8, children 3 and 12, and grandchildren 15 (left of 3) and 1 (right of 12).
Show solution
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
struct tnode
{
int data;
struct tnode *left, *right;
};
struct tnode *new_node(int v)
{
struct tnode *n = malloc(sizeof *n);
if (n == NULL)
exit(1);
n->data = v;
n->left = n->right = NULL;
return n;
}
int find_max(const struct tnode *t)
{
int m, l, r;
if (t == NULL)
return INT_MIN;
m = t->data;
l = find_max(t->left);
r = find_max(t->right);
if (l > m) m = l;
if (r > m) m = r;
return m;
}
int count_internal(const struct tnode *t)
{
if (t == NULL || (t->left == NULL && t->right == NULL))
return 0;
return 1 + count_internal(t->left) + count_internal(t->right);
}
void free_tree(struct tnode *t)
{
if (t) { free_tree(t->left); free_tree(t->right); free(t); }
}
int main(void)
{
struct tnode *root = new_node(8);
root->left = new_node(3);
root->right = new_node(12);
root->left->left = new_node(15);
root->right->right = new_node(1);
printf("Maximum value : %d\n", find_max(root));
printf("Internal nodes: %d\n", count_internal(root));
free_tree(root);
return 0;
}
Maximum value : 15 Internal nodes: 3
Quick Quiz: Binary Tree (MCQ)
-
Maximum children of a node in a binary tree:
A) 1 B) 2 C) 3 D) Any number
-
A node with no children is called a:
A) Root B) Leaf C) Parent D) Sibling
-
Maximum number of nodes at level 3 (root at level 0):
A) 3 B) 6 C) 8 D) 9
-
In array representation, the left child of index i is at:
A) i + 1 B) 2i C) 2i + 1 D) i / 2
-
A tree is a ______ data structure.
A) Linear B) Non-linear C) Static only D) Primitive
Show answers
- B: 2.
- B: leaf.
- C: 23 = 8.
- C: 2i + 1.
- B: non-linear.
Quick Revision for Exams and Interviews
Read this before your exam. The highlighted words are the answer.
Must-remember facts
| Binary tree | Each node has at most 2 children |
|---|---|
| Node in C | data, left, right |
| Leaf | No children (left = right = NULL) |
| Height | Edges on the longest root-to-leaf path |
| Nodes at level L | At most 2L |
| Perfect tree, height h | 2h+1 − 1 nodes |
| Array form | Children 2i+1, 2i+2; parent (i−1)/2 |
Frequently asked questions
- What is a binary tree?
- A non-linear structure in which every node has at most two children, the left and the right child.
- How do you find the height of a binary tree?
- Recursively: height = 1 + max(height(left), height(right)), with height(NULL) = −1.
- What is the difference between a complete and a full binary tree?
- Full: every node has 0 or 2 children. Complete: every level is full except the last, which is filled from the left.
Remember
- Binary tree = family tree with at most two children per parent.
- Tree code = recursion with a NULL base case.
Next Topic
Next lesson: Binary Search Tree in C. You will keep the tree in sorted order so that search, insert and delete become fast.