Trees
Hierarchical data structures that look like upside-down trees. The foundation of file systems, HTML pages, databases, and compilers. Built from scratch in C with all four traversals.
Quick answer
A tree stores data hierarchically: each node has children and no cycles exist. In a binary tree each node has at most a left and a right child. Traversals visit every node in a set order: preorder, inorder, postorder (depth-first) or level order (breadth-first).
- Leaves have no children; their pointers are NULL.
- Inorder is left, root, right; preorder is root first; postorder is root last.
- File systems, the HTML DOM and parsers are trees.
#include <stdio.h>
#include <stdlib.h>
typedef struct Node { int v; struct Node *l, *r; } Node;
Node *node(int v, Node *l, Node *r) { Node *n = malloc(sizeof *n); n->v = v; n->l = l; n->r = r; return n; }
void pre(Node *n) { if (!n) return; printf("%d ", n->v); pre(n->l); pre(n->r); }
void in(Node *n) { if (!n) return; in(n->l); printf("%d ", n->v); in(n->r); }
void post(Node *n) { if (!n) return; post(n->l); post(n->r); printf("%d ", n->v); }
int main(void) {
/* 1
/ \
2 3
/ \
4 5 */
Node *root = node(1, node(2, node(4, NULL, NULL), node(5, NULL, NULL)), node(3, NULL, NULL));
printf("preorder: "); pre(root); printf("\n");
printf("inorder: "); in(root); printf("\n");
printf("postorder: "); post(root); printf("\n");
return 0;
}Output
preorder: 1 2 4 5 3 inorder: 4 2 5 1 3 postorder: 4 5 2 3 1
Every data structure we have covered so far has been linear — arrays, linked lists, stacks, queues all store items in a straight sequence. Trees are different. They store data in a hierarchy — parent–child relationships where one node can connect to multiple others. This single change opens up an entirely new class of problems and solutions.
In this lesson we build binary trees from scratch in C, learn all the vocabulary, implement every traversal, and understand the properties that make trees the backbone of some of the most important systems in computing.
What is a Tree?
A tree is a collection of nodes connected by edges, arranged so that there is exactly one path between any two nodes and no cycles. It looks like a real tree — but drawn upside down with the root at the top and the leaves at the bottom.
🏢 Think of a company org chart
The CEO is at the top. Under the CEO are VPs. Under each VP are managers. Under each manager are engineers. This hierarchy is exactly a tree. The CEO is the root. Engineers with no subordinates are leaves.
Tree Terminology — Words You Must Know
Trees have a vocabulary that everyone uses — in interviews, textbooks, and code reviews. Learn these terms once. You will use them forever.
| Term | Definition | In the org chart example |
|---|---|---|
| Root | The topmost node — has no parent | CEO |
| Node | Any single element in the tree | Any person in the chart |
| Edge | The connection between a parent and child | The line between CEO and VP |
| Parent | The node directly above another node | VP1 is parent of M1 |
| Child | A node directly below another node | M1 and M2 are children of VP1 |
| Leaf | A node with no children | E1, E2, E3, M3 |
| Height | Longest path from root to any leaf (in edges) | CEO → VP1 → M1 → E1 = height 3 |
| Depth | Distance from root to a specific node | M1 has depth 2 |
| Level | All nodes at the same depth | VP1 and VP2 are at level 1 |
| Subtree | Any node and all its descendants | VP1 + all below it = a subtree |
Binary Tree — At Most Two Children
A binary tree is a tree where every node has at most two children — called the left child and the right child. This constraint makes binary trees the most studied and most useful type of tree in computer science. Binary search trees, heaps, expression trees — all are binary trees.
Binary Tree in C — Node Structure
A binary tree node is just like a linked list node — but with two next pointers instead of one. A left pointer and a right pointer. Both are NULL for leaf nodes.
Tree Traversals — Four Ways to Visit Every Node
With a linked list, there is only one way to traverse: start at head and follow next. With a tree, you have choices. The order in which you visit nodes produces completely different sequences — each useful for different problems. There are four standard traversals. Three use recursion (DFS), one uses a queue (BFS).
Inorder Traversal — Left, Root, Right
Inorder visits the left subtree first, then the root, then the right subtree. On a Binary Search Tree, inorder traversal always produces a sorted sequence — this is one of the most important tree properties you will use.
inorder(2) → go left first
inorder(4) → no left → print 4 → no right → return
→ print 2 → go right
inorder(5) → no left → print 5 → no right → return
→ print 1 → go right
inorder(3) → go left first
inorder(6) → no left → print 6 → no right → return
→ print 3 → go right
inorder(7) → no left → print 7 → no right → return
Result: 4 2 5 1 6 3 7
Preorder Traversal — Root, Left, Right
Preorder visits the root first, then the left subtree, then the right subtree. Because you always process the current node before going deeper, preorder is used to copy or serialize a tree — the output can be used to reconstruct the exact same tree.
Postorder Traversal — Left, Right, Root
Postorder visits the left subtree, then right subtree, and processes the root last. Because you handle all children before the parent, postorder is the natural order for deleting a tree (free children before freeing parent) and evaluating expression trees (compute sub-expressions before applying the operator).
Level Order Traversal — BFS with a Queue
Level order visits nodes level by level — all nodes at depth 0 first (root), then all at depth 1, then depth 2, and so on. This is Breadth-First Search (BFS) on a tree. Unlike the other three traversals which use recursion and the call stack, level order needs an explicit queue to track which nodes to visit next.
Height of a Tree and Counting Nodes
Two of the most common tree problems in interviews. Both use recursion naturally — because the height of a tree depends on the height of its subtrees, and the count of nodes is 1 plus the count of the left subtree plus the right.
height(2) = 1 + max(height(4), height(5))
height(4) = 1 + max(-1, -1) = 0
height(5) = 1 + max(-1, -1) = 0
height(2) = 1 + max(0, 0) = 1
height(3) = 1 + max(0, 0) = 1
height(1) = 1 + max(1, 1) = 2 ✓
Trees in the Real World
Errors You Will Hit
All Traversals — Side by Side
| Traversal | Order | Output on example | Method | Key use |
|---|---|---|---|---|
| Inorder | Left → Root → Right | 4 2 5 1 6 3 7 | Recursion | Sorted output from BST |
| Preorder | Root → Left → Right | 1 2 4 5 3 6 7 | Recursion | Copy / serialize tree |
| Postorder | Left → Right → Root | 4 5 2 6 7 3 1 | Recursion | Delete tree, evaluate expressions |
| Level Order | Level by level | 1 2 3 4 5 6 7 | Queue (BFS) | Shortest path, level problems |
You Are Ready for Lesson 13
You now understand trees completely — the terminology, the node structure in C, all four traversals with full traces, height, count, and how trees power real systems from file systems to databases.
In Lesson 13 we cover the Binary Search Tree (BST) — a binary tree with one powerful rule: every left child is smaller than its parent, every right child is larger. This rule makes search, insert, and delete all run in O(log n) on a balanced tree. The BST is the gateway to understanding every advanced tree structure.
🎯 Key Takeaways
- ✓A tree stores data in a hierarchy — parent-child relationships with no cycles
- ✓Binary tree: every node has at most 2 children — left and right
- ✓Each node in C has: data, *left pointer, *right pointer. Both are NULL for leaf nodes
- ✓Inorder (L → Root → R): produces sorted output on a BST — most important traversal
- ✓Preorder (Root → L → R): visits parent before children — used to copy or serialize trees
- ✓Postorder (L → R → Root): visits children before parent — used to delete trees safely
- ✓Level order: visits level by level using a queue (BFS) — gives shortest path in unweighted trees
- ✓Height = longest root-to-leaf path in edges. height(NULL) = -1. height(leaf) = 0
- ✓All traversals are O(n) time — every node visited exactly once
- ✓Trees power file systems (preorder), databases (B-trees), HTML (DOM), and compilers
Quick check
In which order does an inorder traversal visit a node and its subtrees?
HELP US IMPROVE
How was this lesson?
Your note is shared with the Chaduvuko team for review. Please don’t include personal or sensitive information.
Spotted a mistake or something unclear? Suggest a fix on GitHub or email us. Select the text first and it is quoted for you.
Discussion
0Have a better approach? Found something outdated? Share it — your knowledge helps everyone learning here.
