A tree is a data structure that stores items in a hierarchy: one node at the top (the root), and every other node hangs below exactly one parent. A binary tree is a tree where each node has at most two children, called left and right. Tree traversal means visiting every node once in a fixed order: inorder (Left, Root, Right), preorder (Root, Left, Right), postorder (Left, Right, Root), or level order (top to bottom). Each traversal runs in time.
This guide builds everything from scratch in C++: the vocabulary, the different kinds of binary tree, how to create a tree from code and from input, and all four traversals traced step by step on one example tree, so you can compare their outputs side by side.
Tree & Graph series, step 1 of 8. Next: Binary Search Tree (BST) in C++. Full series on the Trees & Graphs topic page.
What Is a Tree in Data Structures?
Arrays, stacks and queues are linear: each element has at most one element before it and one after it. A tree is non-linear and hierarchical: one element can have many elements below it.
Formally, a tree is a set of nodes connected by edges such that:
- There is exactly one special node called the root.
- Every node except the root has exactly one parent.
- There are no cycles: from the root there is exactly one path to any node.
A tree with nodes always has exactly edges, because every node except the root has one edge going up to its parent.
What Is a Tree Node?
A node is the building block of a tree: one object that stores a value and links to its children. In this article every tree is a binary tree (each node has at most two children, called left and right; defined properly below), so a node in C++ looks like this:
struct Node {
int data;
Node* left;
Node* right;
explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};
dataholds the value (aninthere; it could be astringor any type).leftpoints to the root of the left subtree, ornullptrif there is none.rightpoints to the root of the right subtree, ornullptrif there is none.
The constructor sets both pointers to nullptr, so a freshly created node is a leaf. Forgetting to initialise these pointers is one of the most common beginner bugs, because an uninitialised pointer holds garbage and your traversal will crash when it follows it.
A tree is then simply a pointer to its root node: Node* root. An empty tree is root == nullptr. (A node in a general tree, where any number of children is allowed, would store a list such as vector<Node*> children instead of left and right.)
Tree Terminology
Every term below is marked on the diagram.
| Term | Meaning | In the diagram |
|---|---|---|
| Root | The only node with no parent | A |
| Parent | A node directly above another node | B is the parent of E and F |
| Child | A node directly below another node | E and F are children of B |
| Sibling | Nodes with the same parent | E and F; also B, C and D |
| Leaf (external node) | A node with no children | C, E, F, G, I |
| Internal node | A node with at least one child | A, B, D, H |
| Edge | The link between a parent and a child | A–B |
| Path | A sequence of nodes joined by edges | A → D → H → I |
| Depth of a node | Number of edges from the root down to that node | depth(A) = 0, depth(I) = 3 |
| Height of a node | Number of edges on the longest path from that node down to a leaf | height(D) = 2, height(I) = 0 |
| Height of the tree | Height of the root | 3 |
| Level | All nodes at the same depth | level 1 = B, C, D |
| Subtree | A node together with all of its descendants | the box around D, G, H, I |
| Degree of a node | Number of children of that node | degree(A) = 3, degree(D) = 2 |
| Degree of a tree | The largest degree of any node | 3 |
Depth vs height, the one-line version: depth is measured from the root down to a node; height is measured from a node down to its deepest leaf. The root has depth 0; every leaf has height 0.
Watch out for conventions. Most textbooks and this site count height in edges, so a single node has height 0 and an empty tree has height −1. Some courses and LeetCode’s “maximum depth” count nodes instead, so a single node has height 1. Both are fine; just state which one you use in an exam answer.
Real-World Applications of Trees
You use trees every day, usually without noticing:
| Where | What the tree stores |
|---|---|
| File systems | Folders contain files and sub-folders |
| HTML / the DOM | <html> contains <body>, which contains <div>s |
| Compilers | Expressions become expression trees / syntax trees |
| Databases | B-trees and B+ trees index millions of rows |
std::map, std::set | Usually a red-black tree (a self-balancing BST) |
| Priority queues | A binary heap, which is a complete binary tree stored in an array |
| Networking | Routing tables, spanning trees |
| AI and games | Decision trees, game trees (minimax) |
| Compression | Huffman coding trees |
What Is a Binary Tree?
A binary tree is a tree in which every node has at most two children, and the two child positions are distinguished: the left child and the right child. A node with only a right child is a different tree from a node with only a left child.
Here is the binary tree used for every example in this article:
- 1 is the root.
- 2 is the left child of 1, and 3 is the right child of 1.
- 3 has no left child (
nullptr) and a right child, 6. - 5 has a left child, 7, and no right child.
- Leaves: 4, 7 and 6. Height: 3 (path 1 → 2 → 5 → 7).
Useful binary tree properties
For a binary tree with height (in edges) and nodes:
- Level has at most nodes (level 0 has 1, level 1 has 2, level 2 has 4, …).
- The tree has at most nodes.
- The minimum possible height is ; the maximum is (a chain).
- In any binary tree, if is the number of leaves and the number of nodes with two children, then .
- A tree with nodes has edges and
nullptrchild pointers.
Types of Binary Trees
These five names are the most common source of confusion in exams and interviews, so each panel below is chosen to show a tree that is one type but not another.
| Type | Rule | Quick test |
|---|---|---|
| Full (proper, strict) | Every node has 0 or 2 children | No node has exactly one child |
| Complete | Every level is completely filled except possibly the last, and the last level is filled from the left | Level-order listing has no gap before the last node |
| Perfect | All internal nodes have 2 children and all leaves are at the same depth | Exactly nodes |
| Balanced (height-balanced) | At every node, the heights of the left and right subtrees differ by at most 1 | Used by AVL trees |
| Degenerate / skewed | Every internal node has exactly one child | Looks like a linked list; height |
How they relate:
- Every perfect tree is both full and complete.
- A full tree need not be complete (first panel: the last level is not filled from the left).
- A complete tree need not be full (second panel: node 3 has only one child).
- Every complete tree is balanced, but a balanced tree need not be complete (fourth panel).
- A skewed tree is the worst case: operations that should take take . You will see why this matters in the BST guide.
Tree Representation in C++
There are two standard ways to store a binary tree.
1. Linked representation (nodes and pointers)
Each node is an object holding the data and two pointers, exactly the struct Node from What Is a Tree Node?. This is what you will use 95% of the time.
2. Array representation
Store the nodes level by level in an array. With 0-based indexing, the node at index i has:
- left child at
2*i + 1 - right child at
2*i + 2 - parent at
(i - 1) / 2
The example tree in level order with gaps is [1, 2, 3, 4, 5, _, 6, _, _, 7]. This is perfect for complete trees (that is how a binary heap is stored) but wastes space on sparse trees: a skewed tree with nodes can need about slots.
How to Create a Binary Tree in C++
To build the example tree, create each node with new and connect it to its parent by assigning left or right:
Node* root = new Node(1); // the root
root->left = new Node(2); // 1's left child
root->right = new Node(3); // 1's right child
root->left->left = new Node(4); // 2's left child
root->left->right = new Node(5); // 2's right child
root->right->right = new Node(6); // 3's RIGHT child (3 has no left child)
root->left->right->left = new Node(7); // 5's left child
Read each line as “go to a node, then attach a new child on one side”. root->left->right means “the right child of the left child of the root”, which is node 5.
Because every node was created with new, the program must delete them when it is done. The safe order is postorder: delete both children before the parent, otherwise you lose the pointers to the children.
void destroy(Node* root) {
if (root == nullptr) {
return;
}
destroy(root->left);
destroy(root->right);
delete root; // children are already gone, so this is safe
}
How to Build a Tree From Input
Typing pointer chains does not scale. Programs (and lab exams) usually read a tree from input. The most common format lists the tree in level order, using -1 for a missing child, the same idea LeetCode uses with null.
The algorithm uses a queue: the queue holds the nodes that are still waiting to receive their children.
- Read the first value and make it the root. Push the root into the queue.
- While the queue is not empty: pop a node, read two values. If the first is not
-1, create the left child and push it. If the second is not-1, create the right child and push it.
#include <iostream>
#include <queue>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};
// Reads a tree in level order; -1 means "no child here".
Node* buildLevelOrder() {
int value;
if (!(cin >> value) || value == -1) {
return nullptr;
}
Node* root = new Node(value);
queue<Node*> pending; // nodes whose children have not been read yet
pending.push(root);
while (!pending.empty()) {
Node* current = pending.front();
pending.pop();
int leftValue, rightValue;
if (!(cin >> leftValue >> rightValue)) {
break; // input ended early
}
if (leftValue != -1) {
current->left = new Node(leftValue);
pending.push(current->left);
}
if (rightValue != -1) {
current->right = new Node(rightValue);
pending.push(current->right);
}
}
return root;
}
void inorder(Node* root) {
if (root == nullptr) {
return;
}
inorder(root->left);
cout << root->data << ' ';
inorder(root->right);
}
void destroy(Node* root) {
if (root == nullptr) {
return;
}
destroy(root->left);
destroy(root->right);
delete root;
}
int main() {
Node* root = buildLevelOrder();
cout << "Inorder: ";
inorder(root);
cout << '\n';
destroy(root);
}
Input:
1 2 3 4 5 -1 6 -1 -1 7 -1 -1 -1 -1 -1
Output:
Inorder: 4 2 7 5 1 3 6
Count the tokens: one for the root plus two for each of the 7 nodes gives 15 values. Every real node eventually gets popped and reads exactly two values, which is why leaves are followed by -1 -1.
Tree Traversal: Inorder, Preorder, Postorder and Level Order
A traversal visits every node exactly once. Linear structures have one natural order; a tree has several. The three depth-first traversals differ only in when the root is visited relative to its two subtrees:
| Traversal | Order | Mnemonic |
|---|---|---|
| Preorder | Root, Left, Right | root pre (before) the subtrees |
| Inorder | Left, Root, Right | root in between the subtrees |
| Postorder | Left, Right, Root | root post (after) the subtrees |
| Level order | Level 0, then level 1, then level 2, …, left to right | breadth-first |
The left subtree is always handled before the right subtree in all of them. All four results for our example tree:
| Traversal | Output |
|---|---|
| Preorder | 1 2 4 5 7 3 6 |
| Inorder | 4 2 7 5 1 3 6 |
| Postorder | 4 7 5 2 6 3 1 |
| Level order | 1 2 3 4 5 6 7 |
Use the player below to watch each traversal run. The call stack shows which recursive calls are active, from the outermost call on the left to the current call on the right. The dashed nodes are on the stack but not yet printed.
- Output
Inorder Traversal (Left, Root, Right)
Rule: traverse the left subtree, visit the root, traverse the right subtree.
Step by step from the root:
- At 1: go left to 2 first. At 2: go left to 4. 4 has no left child, so print 4; it has no right child either, so return.
- Back at 2: its left subtree is done, so print 2. Then go right to 5.
- At 5: go left to 7. Print 7. Back at 5: print 5. 5 has no right child.
- 2’s subtree is finished. Back at 1: print 1, then go right to 3.
- At 3: there is no left child, so print 3. Go right to 6 and print 6.
Inorder: 4 2 7 5 1 3 6
Why it matters: on a binary search tree, inorder prints the keys in sorted order. That single fact powers many BST interview questions.
Preorder Traversal (Root, Left, Right)
Rule: visit the root, traverse the left subtree, traverse the right subtree.
- Print 1, then go left.
- Print 2, go left: print 4 (a leaf).
- Back at 2, go right: print 5, go left: print 7.
- Left half of the tree is done. Back at 1, go right: print 3. No left child; go right: print 6.
Preorder: 1 2 4 5 7 3 6
Why it matters: preorder records a parent before its children, so it is used to copy or serialize a tree. The first value of a preorder sequence is always the root.
Postorder Traversal (Left, Right, Root)
Rule: traverse the left subtree, traverse the right subtree, visit the root.
- Go all the way left: print 4 (no children).
- Back at 2, its right subtree is 5. 5’s left subtree is 7: print 7. 5 has no right child: print 5.
- Both subtrees of 2 are done: print 2.
- Back at 1, go right to 3. No left child; right child 6: print 6. Then print 3.
- Finally print 1.
Postorder: 4 7 5 2 6 3 1
Why it matters: postorder finishes the children before the parent, so it is the right order to delete a tree, compute heights and sizes (a node needs its children’s answers first), and evaluate an expression tree. The last value is always the root.
Level Order Traversal (Brief Introduction)
Rule: visit nodes level by level, left to right. Instead of recursion, level order uses a queue: dequeue a node, print it, enqueue its children.
| Step | Dequeue and print | Enqueue | Queue after (front → back) |
|---|---|---|---|
| start | 1 | [1] | |
| 1 | 1 | 2, 3 | [2, 3] |
| 2 | 2 | 4, 5 | [3, 4, 5] |
| 3 | 3 | 6 | [4, 5, 6] |
| 4 | 4 | [5, 6] | |
| 5 | 5 | 7 | [6, 7] |
| 6 | 6 | [7] | |
| 7 | 7 | [] |
Level order: 1 2 3 4 5 6 7
Level order is breadth-first search (BFS) applied to a tree, while preorder, inorder and postorder are all forms of depth-first search (DFS). Both ideas get their own guide in What Are DFS and BFS?.
Recursive Traversal Implementation in C++
Each recursive traversal has the same shape:
- Base case: if the node is
nullptr(an empty subtree), there is nothing to visit, so return. - Recursive case: make two recursive calls (left subtree, right subtree) and print the current node before, between, or after them.
That is the only difference between the three functions below. Here is a complete program that builds the example tree, runs all four traversals and computes a few basic properties:
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
explicit Node(int value) : data(value), left(nullptr), right(nullptr) {}
};
void preorder(Node* root) {
if (root == nullptr) {
return; // base case: empty subtree
}
cout << root->data << ' '; // Root
preorder(root->left); // Left
preorder(root->right); // Right
}
void inorder(Node* root) {
if (root == nullptr) {
return;
}
inorder(root->left); // Left
cout << root->data << ' '; // Root
inorder(root->right); // Right
}
void postorder(Node* root) {
if (root == nullptr) {
return;
}
postorder(root->left); // Left
postorder(root->right); // Right
cout << root->data << ' '; // Root
}
void levelOrder(Node* root) {
if (root == nullptr) {
return;
}
queue<Node*> q;
q.push(root);
while (!q.empty()) {
Node* current = q.front();
q.pop();
cout << current->data << ' ';
if (current->left) {
q.push(current->left);
}
if (current->right) {
q.push(current->right);
}
}
}
// Height in edges: empty tree = -1, single node = 0.
int height(Node* root) {
if (root == nullptr) {
return -1;
}
return 1 + max(height(root->left), height(root->right));
}
int countNodes(Node* root) {
if (root == nullptr) {
return 0;
}
return 1 + countNodes(root->left) + countNodes(root->right);
}
int countLeaves(Node* root) {
if (root == nullptr) {
return 0;
}
if (root->left == nullptr && root->right == nullptr) {
return 1;
}
return countLeaves(root->left) + countLeaves(root->right);
}
void destroy(Node* root) {
if (root == nullptr) {
return;
}
destroy(root->left);
destroy(root->right);
delete root;
}
int main() {
Node* 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->left->right->left = new Node(7);
cout << "Preorder: ";
preorder(root);
cout << '\n';
cout << "Inorder: ";
inorder(root);
cout << '\n';
cout << "Postorder: ";
postorder(root);
cout << '\n';
cout << "Level order: ";
levelOrder(root);
cout << '\n';
cout << "Height (edges): " << height(root) << '\n';
cout << "Nodes: " << countNodes(root) << '\n';
cout << "Leaves: " << countLeaves(root) << '\n';
destroy(root);
}
Output:
Preorder: 1 2 4 5 7 3 6
Inorder: 4 2 7 5 1 3 6
Postorder: 4 7 5 2 6 3 1
Level order: 1 2 3 4 5 6 7
Height (edges): 3
Nodes: 7
Leaves: 3
How the recursion actually runs
Take inorder(root) on node 2’s subtree. The calls nest like this (indentation = call depth):
inorder(2)
inorder(4)
inorder(nullptr) -> returns
print 4
inorder(nullptr) -> returns
print 2
inorder(5)
inorder(7)
inorder(nullptr) -> returns
print 7
inorder(nullptr) -> returns
print 5
inorder(nullptr) -> returns
Every node causes exactly one call, and every nullptr child causes one call that returns immediately. That is real calls plus empty calls, so the work is linear.
Want the iterative versions with an explicit stack (a favourite viva question)? They are written out in the tree exam questions guide.
Time and Space Complexity
| Operation | Time | Extra space |
|---|---|---|
| Preorder / inorder / postorder (recursive) | call stack | |
| Level order (queue) | , where is the widest level | |
| Height, count nodes, count leaves | ||
| Build from level-order input | queue |
Here is the number of nodes and the height. Each node is visited once, so time is . The space is the recursion depth: for a balanced tree, but for a skewed tree, where a deep enough chain (around a hundred thousand nodes) can overflow the call stack. For a perfect tree, the last level holds about nodes, so level order’s queue can reach .
Common Mistakes Beginners Make
- Missing the base case. Without
if (root == nullptr) { return; }the function dereferences a null pointer and crashes on the first leaf. - Uninitialised child pointers.
Node* n = new Node;with no constructor leavesleftandrightas garbage. Always set them tonullptr. - Confusing height and depth, or mixing the edge and node conventions in one answer. Say “height in edges” explicitly.
- Checking only the left child for a leaf. A leaf needs both
left == nullptrandright == nullptr; node 3 in our tree has no left child but is not a leaf. - Losing the root. Writing
root = root->left;while building or traversing overwrites your only handle to the tree. Use a separatecurrentpointer. - Deleting the parent first.
delete root; destroy(root->left);reads freed memory. Delete in postorder. - Treating every binary tree as a BST. Searching left/right by comparing values only works when the tree has the BST property; in a general binary tree you must search both subtrees.
- Assuming one traversal identifies a tree. Different trees can share a preorder. You need inorder plus preorder or postorder to rebuild a tree uniquely (with distinct values).
Practice Problems
Try them in this order; each builds on the previous one.
| # | Problem | Skill |
|---|---|---|
| 1 | Binary Tree Inorder Traversal (LeetCode 94) | Recursion template |
| 2 | Binary Tree Preorder Traversal (LeetCode 144) | Visit before recursing |
| 3 | Binary Tree Postorder Traversal (LeetCode 145) | Visit after recursing |
| 4 | Binary Tree Level Order Traversal (LeetCode 102) | Queue, level by level |
| 5 | Maximum Depth of Binary Tree (LeetCode 104) | Postorder-style return values |
| 6 | Same Tree (LeetCode 100) | Recursing on two trees at once |
| 7 | Construct Binary Tree from Preorder and Inorder (LeetCode 105) | Using traversal properties |
Offline exercises, using the example tree from this article:
- Without running code, write the preorder of the tree after removing node 7. (Answer:
1 2 4 5 3 6.) - Add a left child 8 to node 3. What are the new inorder and level order? (Answers:
4 2 7 5 1 8 3 6and1 2 3 4 5 8 6 7.) - Is the example tree full? Complete? Height-balanced?
- Not full: nodes 3 and 5 each have exactly one child.
- Not complete: in level order, the empty left slot of node 3 comes before node 6.
- Balanced: check every node. At 1: left height 2, right height 1. At 2: 0 and 1. At 3: −1 and 0. At 5: 0 and −1. Every difference is at most 1, so it is height-balanced.
The last answer is a good reminder to check the balance condition at every node, not just the root.
Frequently Asked Questions
What is the difference between a tree and a binary tree?
A general tree lets each node have any number of children. A binary tree limits each node to at most two, and labels them left and right. Every binary tree is a tree, but not every tree is a binary tree.
Which traversal gives sorted output?
Inorder, but only for a binary search tree. On an ordinary binary tree, inorder output has no special order.
Can I rebuild a binary tree from one traversal?
Not in general. Preorder alone, for example, cannot tell whether the second node is a left or a right child. Inorder together with preorder (or with postorder) rebuilds a tree with distinct values uniquely. Preorder plus postorder is enough only for full binary trees.
Is level order traversal DFS or BFS?
BFS. Preorder, inorder and postorder are DFS.
Next Steps
You now know how a binary tree is stored and walked. Continue the series:
- Next: Binary Search Tree (BST) in C++: add an ordering rule and get fast search, insert and delete.
- Then test yourself with Tree Interview Questions.
- Preparing for a university exam? See Tree Questions for University Exams in Bangladesh.