Arrays and hash tables are great for storing flat collections of data. But what about data that’s naturally hierarchical — like a company org chart, a file system, or the rules in a decision-making process? That’s where trees come in.
Trees are one of the most widely used data structures in computer science, and a solid understanding of them will help you with everything from database internals to coding interviews. In this post, we’ll cover what trees are, the most important types, and how to traverse them in four different ways.
What Is a Tree?
A tree is a hierarchical data structure made up of nodes connected by edges. Unlike graphs (which can have cycles and arbitrary connections), trees have a strict parent-child structure with no cycles.
Here’s the essential vocabulary you’ll need:
| Term | Definition |
|---|---|
| Root | The topmost node — every tree has exactly one |
| Parent / Child | A node connected above (parent) or below (child) another |
| Siblings | Nodes that share the same parent |
| Leaf Node | A node with no children |
| Height | Length of the longest path from the root to any leaf |
| Depth | Distance from the root to a given node |
A key distinction: trees are a special case of graphs — specifically, a connected, acyclic, directed graph. Every tree is a graph, but not every graph is a tree.
Binary Tree
A binary tree is a tree where each node has at most two children — called the left child and the right child.
A
/ \
B C
/ \ \
D E F
There are several subtypes worth knowing:
| Type | Rule |
|---|---|
| Full Binary Tree | Every node has exactly 0 or 2 children |
| Complete Binary Tree | All levels filled except possibly the last, which fills left to right |
| Perfect Binary Tree | All internal nodes have 2 children; all leaves at the same level |
| Skewed Binary Tree | Every node has only one child (degenerates into a linked list) |
Complexity
A plain binary tree has no ordering rules, so searching for a value means checking every node in the worst case.
| Operation | Average | Worst |
|---|---|---|
| Search | O(n) | O(n) |
| Insert | O(n) | O(n) |
| Delete | O(n) | O(n) |
This is where the Binary Search Tree improves things significantly.
Binary Search Tree (BST)
A Binary Search Tree is a binary tree with one extra rule: for every node, all values in its left subtree are less than or equal to it, and all values in its right subtree are greater.
50
/ \
30 70
/ \ / \
20 40 60 80
This ordering property is powerful — it lets you eliminate half the tree at every step, just like binary search on a sorted array.
Complexity
| Operation | Average | Worst |
|---|---|---|
| Search | O(log n) | O(n) |
| Insert | O(log n) | O(n) |
| Delete | O(log n) | O(n) |
The catch is the worst case. If you insert values in sorted order (e.g., 1, 2, 3, 4, 5), the BST degenerates into a straight line — effectively a linked list — and you lose the O(log n) advantage. This is why balanced BSTs (like AVL trees or Red-Black trees) exist: they automatically restructure themselves to stay balanced and keep worst-case operations at O(log n).
N-ary Tree
While binary trees limit each node to two children, an N-ary tree allows any number of children per node. Instead of dedicated left and right pointers, each node holds an array of children.
cpp
struct NaryNode {
int value;
vector<NaryNode*> children;
};
File systems are a classic N-ary tree: a folder can contain any number of files or subfolders. The same traversal logic applies — you just iterate over the children array instead of two fixed pointers.
Tree Traversal
To search, insert, or delete in a tree, you need to visit the nodes in some order. There are four standard traversal methods, each visiting nodes in a different sequence.
All of them use the same TreeNode struct:
cpp
struct TreeNode {
int value;
TreeNode *left;
TreeNode *right;
};
We’ll use this tree for all four examples:
A
/ \
B C
/ \ \
D E F
1. In-Order Traversal (Left → Root → Right)
Visit the left subtree first, then the current node, then the right subtree. On a BST, this always produces values in sorted ascending order — which makes it extremely useful.
Output on example tree: D, B, E, A, C, F
cpp
void inorder(TreeNode *node) {
if (node == nullptr) return;
inorder(node->left); // 1. go left
print(node->value); // 2. visit current
inorder(node->right); // 3. go right
}
Use case: Printing all values of a BST in sorted order.
2. Pre-Order Traversal (Root → Left → Right)
Visit the current node first, then recurse left, then recurse right. The root is always the first node visited.
Output on example tree: A, B, D, E, C, F
cpp
void preorder(TreeNode *node) {
if (node == nullptr) return;
print(node->value); // 1. visit current
preorder(node->left); // 2. go left
preorder(node->right); // 3. go right
}
Use case: Copying or serializing a tree — since the root is printed before its subtrees, you can reconstruct the tree from a pre-order sequence.
3. Post-Order Traversal (Left → Right → Root)
Recurse left, recurse right, then visit the current node last. The root is always the last node visited.
Output on example tree: D, E, B, F, C, A
cpp
void postorder(TreeNode *node) {
if (node == nullptr) return;
postorder(node->left); // 1. go left
postorder(node->right); // 2. go right
print(node->value); // 3. visit current
}
Use case: Deleting a tree (delete children before parent) or evaluating expression trees (compute sub-expressions before the operator).
4. Level-Order Traversal (Level by Level)
Unlike the three traversals above — which all use recursion and go deep first — level-order visits nodes one level at a time, left to right. This is essentially BFS applied to a tree, and it uses a queue instead of recursion.
Output on example tree: A, B, C, D, E, F
cpp
void levelorder(TreeNode *node) {
if (node == nullptr) return;
queue<TreeNode*> q;
q.push(node);
while (!q.empty()) {
int size = q.size(); // number of nodes at this level
for (int i = 0; i < size; ++i) {
TreeNode *curr = q.front();
q.pop();
cout << curr->value << " ";
if (curr->left != nullptr) q.push(curr->left);
if (curr->right != nullptr) q.push(curr->right);
}
cout << endl; // newline after each level
}
}
Use case: Finding the shortest path in a tree, printing trees level by level, or anything where proximity to the root matters.
Traversal Comparison at a Glance
Using the same tree for all four:
A
/ \
B C
/ \ \
D E F
| Traversal | Order | Output | Key Use Case |
|---|---|---|---|
| In-order | Left → Root → Right | D, B, E, A, C, F | Sorted output from BST |
| Pre-order | Root → Left → Right | A, B, D, E, C, F | Tree serialization / copying |
| Post-order | Left → Right → Root | D, E, B, F, C, A | Deletion, expression evaluation |
| Level-order | Level by level | A, B, C, D, E, F | Shortest path, BFS-style problems |
A simple memory trick: the name tells you when the current node is visited relative to its children.
- Pre-order → current node before children
- In-order → current node between children
- Post-order → current node after children
Summary
Trees are essential for modeling hierarchical data, and understanding them opens the door to a huge range of algorithms and system designs:
- A tree is a hierarchical, acyclic structure with a single root
- A binary tree limits each node to two children; a BST adds an ordering rule for O(log n) average search
- N-ary trees generalize to any number of children, stored as an array
- In-order, pre-order, and post-order traversals use recursion and differ only in when the current node is visited
- Level-order traversal uses a queue and visits nodes level by level
Mastering these four traversal patterns also sets you up for more advanced topics like heap data structures, segment trees, and tries — all of which build on these same fundamentals.
This post is part of a series on core data structures and algorithms. → Hash Tables Explained → Graph Data Structures: A Beginner’s Guide → BFS & DFS: Graph Traversal Algorithms → BFS & DFS: Graph Traversal Algorithms