Binary trees and their representation
Clear, exam‑focused notes on binary trees: definitions, properties, array and pointer representations, derivations, C++ examples, common mistakes and practice questions.
Drafted with Aria, reviewed by the AiCanCode.org team · Updated . How we write and check our notes. Spotted an error? Use Give Feedback at the bottom of the page.
Why it matters
Binary trees are a core data structure used by engineers for searching, sorting, expression parsing, and representing hierarchical data (like file systems, parse trees and many algorithmic data structures such as binary search trees, heaps and AVL trees). Understanding representations (pointer-based, array-based, threaded) helps you choose the right implementation for memory and performance constraints.
Key ideas
We build from first principles and clearly define each term before using it.
Binary tree: a finite set of nodes that is either empty or consists of a node called the root together with two disjoint binary trees called the left subtree and right subtree of the root. (This is the recursive definition.)
Node: an element that stores data (key) and pointers/links to its children (in pointer representation) or an index (in array representation).
Root: the top node of a non-empty tree which has no parent.
Parent and child: if node A has a link to node B as its left or right link, then A is the parent of B and B is a child of A.
Leaf (external) node: a node with no children.
Internal node: a node with at least one child.
Degree of a node: the number of children a node has (0, 1 or 2 in a binary tree).
Path: a sequence of nodes where each adjacent pair is connected by an edge (parent-child link).
Depth (level) of a node: number of edges from the root to the node. (Root level = 0 under our convention.) Be explicit in answers: if your university uses root level = 1, state that.
Height of a node: number of edges on the longest path from that node down to a leaf. The height of the tree = height of the root. Under our convention, a tree with single node has height 0.
Size (n): number of nodes in the tree.
Full (proper) binary tree: every node has degree 0 or 2 (no node has exactly one child).
Perfect binary tree: a full binary tree in which all leaves are at the same depth (every level completely filled).
Complete binary tree: all levels are completely filled except possibly the last level; the last level has nodes filled from left to right with no gaps.
Threaded binary tree: a binary tree in which null child pointers are replaced by threads pointing to the node's inorder predecessor and/or successor (single- or double-threaded). A tag bit per pointer distinguishes a real child link from a thread; benefit: inorder traversal without recursion/stack.
Skewed tree: every internal node has exactly one child (all nodes form a chain). If every node only has a left child it's called left-skewed.
Subtree: for a node X, the tree consisting of X and all its descendants.
Ancestor / Descendant: X is an ancestor of Y if X is on the path from the root to Y; Y is a descendant of X.
Traversal orders (definitions and exact visit order for a node N):
- Preorder: visit N, then traverse left subtree (preorder), then traverse right subtree (preorder).
- Inorder: traverse left subtree (inorder), visit N, then traverse right subtree (inorder).
- Postorder: traverse left subtree (postorder), traverse right subtree (postorder), then visit N.
- Level-order (breadth-first): visit nodes level by level from top to bottom and left to right at each level.
Important theorems and derivations commonly asked in exams:
Maximum number of nodes at level i (root at level 0): At most
2^inodes. Assumption: binary tree (each node has at most two children). Reason: each node at level i-1 can have at most 2 children.Maximum number of nodes in a binary tree of height h (height = number of edges on longest root–leaf path):
- Levels = h + 1.
- Total nodes ≤ 1 + 2 + 4 + ... + 2^h = 2^(h+1) − 1.
- Derivation: geometric series S = sum_{i=0..h} 2^i = (2^(h+1)−1)/(2−1) = 2^(h+1)−1. State assumptions (each level filled to maximum).
Relationship between edges and nodes: Any non-empty tree with n nodes has exactly n − 1 edges (because edges connect nodes into a tree). Use this when counting pointer references.
Null pointer count theorem (pointer representation): If each node stores exactly two child pointers (left and right) and null is used for absent children, then a non-empty binary tree with n nodes has exactly n + 1 null child pointers. Proof: total child pointer slots = 2n. Non-null child pointers = number of edges = n − 1. So null pointers = 2n − (n − 1) = n + 1. State assumption: non-empty tree; each node has two pointer fields.
Array (implicit) representation indexing (0-based index): For an array A where root is at index 0 and the tree is represented in level-order (this representation is correct for complete binary trees):
- Left child of node at index i is at index
2*i + 1(if within array bounds and not a placeholder). - Right child is at index
2*i + 2. - Parent of node at index i (i > 0) is at index
floor((i - 1)/2). Also state the 1-based variant (root at index 1): left =2*i, right =2*i + 1, parent =floor(i/2). These formulas apply only when the array is used in level-order and the tree is complete or when you use placeholders for missing nodes.
- Left child of node at index i is at index
Diagram instructions (what to draw and label for an exam):
- Draw a small binary tree of 7 nodes to illustrate a perfect tree: draw nodes as circles, place root at top labeled with its key, draw left and right children below and connect edges. Label levels 0,1,2 at left margin. For pointer representation, show each node as a box with fields [data | left | right] and draw arrows for left/right pointers (NULL as crossed arrow). For array representation, draw the level-order array and draw arrows from array index to indices
2*i+1and2*i+2(0-based). This diagram helps answer questions about index mapping and traversal.
Formulas
Max nodes at level i = 2^i — i is level (root level = 0). No unit. Applies to binary trees where each node may have up to two children.
Max nodes in tree of height h = 2^(h+1) − 1 — h is height measured as number of edges on longest root→leaf path. No unit. Assumes full filling of levels 0..h.
Min possible height (edges) for n nodes = ceil(log2(n + 1)) − 1 — attained by a perfect tree.
Max possible height (edges) for n nodes = n − 1 — attained by a skewed tree.
In a perfect binary tree of height h: leaves = 2^h; internal nodes = 2^h − 1.
Edges (e) in a non-empty tree = n − 1 — n is number of nodes. Unitless.
Null child pointers = 2n − e = n + 1 — for pointer-based binary tree with two child fields per node; e = n − 1. Assumes non-empty tree.
Array-indexing (0-based) syntax to remember:
left_index(i) = 2*i + 1 — index of left child of node at index i (if present).
right_index(i) = 2*i + 2 — index of right child of node at index i (if present).
parent_index(i) = (i - 1) / 2 — integer division; defined only for i > 0.
Memory-cost reminders (pointer representation): each node stores data and two pointers. If pointer size = P bytes and data size = D bytes, memory ≈ n*(D + 2*P) (ignoring allocator overhead); state this estimate in exam answers.
- In a complete binary tree with n nodes (0-based): internal nodes = floor(n/2); leaves = ceil(n/2); last internal node index = floor(n/2) − 1.
- In any full (proper) binary tree: number of leaves L equals number of internal nodes I plus 1 (L = I + 1).
- For any binary tree with n nodes, the number of leaves L satisfies L ≤ floor((n + 1)/2).
Worked examples
Example 1 — Derivation (theory): Maximum nodes in a binary tree of height 3 (height measured in edges). Step-by-step:
- Levels = h + 1 = 3 + 1 = 4 levels (levels 0,1,2,3).
- Nodes per level: level 0 → 1, level 1 → 2, level 2 → 4, level 3 → 8.
- Total = 1 + 2 + 4 + 8 = 15.
- Formula: 2^(3+1) − 1 = 2^4 − 1 = 16 − 1 = 15. Final answer: 15.
Example 2 — C++ program: build linked binary tree from a level-order array (-1 used to mark NULL). This implementation treats input array positions as level-order slots (works for complete layouts or arrays with placeholders). It then prints the three depth-first traversals (preorder, inorder, postorder).
#include <bits/stdc++.h>
using namespace std;
struct Node {
int key;
Node *left, *right;
Node(int k): key(k), left(nullptr), right(nullptr) {}
};
Node* buildFromLevelOrder(const vector<int>& A) {
int n = (int)A.size();
if (n==0) return nullptr;
vector<Node*> nodes(n, nullptr);
for (int i = 0; i < n; ++i) {
if (A[i] != -1) nodes[i] = new Node(A[i]);
}
for (int i = 0; i < n; ++i) {
if (!nodes[i]) continue;
int L = 2*i + 1;
int R = 2*i + 2;
if (L < n) nodes[i]->left = nodes[L];
if (R < n) nodes[i]->right = nodes[R];
}
return nodes[0]; // root (may be nullptr if A[0]==-1)
}
void preorder(Node* r) { if (!r) return; cout<<r->key<<" "; preorder(r->left); preorder(r->right); }
void inorder(Node* r) { if (!r) return; inorder(r->left); cout<<r->key<<" "; inorder(r->right); }
void postorder(Node* r) { if (!r) return; postorder(r->left); postorder(r->right); cout<<r->key<<" "; }
int main(){
// Input format: n followed by n integers (use -1 to indicate absent node in that slot)
int n; if (!(cin>>n)) return 0;
vector<int> A(n);
for (int i=0;i<n;++i) cin>>A[i];
Node* root = buildFromLevelOrder(A);
cout<<"Preorder: "; preorder(root); cout<<"\n";
cout<<"Inorder: "; inorder(root); cout<<"\n";
cout<<"Postorder: "; postorder(root); cout<<"\n";
return 0;
}
Sample input (represents a perfect tree 1..7):
7
1 2 3 4 5 6 7
Exact output:
Preorder: 1 2 4 5 3 6 7
Inorder: 4 2 5 1 6 3 7
Postorder: 4 5 2 6 7 3 1
(Observe spaces: each number followed by a space, then newline.)
Example 3 — array representation example (index mapping and traversal). We give a short C++ program that performs inorder traversal by index on an array representing a complete tree with root at index 0.
#include <bits/stdc++.h>
using namespace std;
vector<int> A;
void inorder_index(int i) {
if (i >= (int)A.size() || A[i] == -1) return;
inorder_index(2*i + 1);
cout<<A[i]<<" ";
inorder_index(2*i + 2);
}
int main(){
int n; if(!(cin>>n)) return 0; A.resize(n);
for(int i=0;i<n;++i) cin>>A[i];
inorder_index(0);
cout<<"\n";
}
Sample input:
7
1 2 3 4 5 6 7
Output:
4 2 5 1 6 3 7
Note: array-based recursion will only be valid when the array layout corresponds to the tree positions (use -1 placeholders if the tree is not complete).
Common mistakes
- Using array index formulas without stating 0-based or 1-based indexing. The factor of 1 shifts formulas.
- Applying array representation to a non-complete tree without using placeholders; missing node positions break the index relationships.
- Forgetting that number of edges = n − 1 only for non-empty trees; for empty tree handle separately.
- Counting null pointers incorrectly – forget to subtract edges when computing null links.
- In code, not checking array bounds for child indices (2*i+1 may exceed array length).
For your exam
Kinds of questions you will see:
- Definitions and short notes: define binary tree variants (full, perfect, complete), explain traversal orders, compare array vs pointer representations.
- Derivations: prove max nodes at level i or derive max nodes for tree height h (use geometric series). Prove null-pointer count theorem.
- Numerical/diagram questions: draw a binary tree and label nodes with levels or heights; convert between array and pointer representation for a given level-order array.
- Programs: implement traversals, build tree from level-order array or linked insertion, print traversals for sample input. For full marks include input format, brief complexity analysis (time O(n), space O(h) recursion stack for depth-first), and mention assumptions.
- Complexity questions: state time complexity of traversals (O(n)), and memory costs for pointer vs array representations.
What a full‑marks answer includes:
- Clear definitions with stated conventions (levels start at 0 or 1; height measured in edges or nodes).
- Correct derivation steps (show summation or induction when required).
- Diagrams where asked, with nodes, levels, and indices labeled as instructed.
- For code: correct input/output format, correct index checks and null handling, and complexity comments.
Quick check
- For a binary tree where root is at level 0, how many nodes are possible at level 4?
- What is the parent index of node at index 10 in a 0-based array representation?
- State the number of null child pointers in a non-empty binary tree with 9 nodes.
Answers: 1) 2^4 = 16. 2) floor((10 − 1)/2) = floor(9/2) = 4. 3) n + 1 = 9 + 1 = 10.
Finished this topic? Mark it so your progress, study plan and readiness keep up.
Stuck on something here?