Skip to content
Shafin Chowdhury
Go back

Trees, Binary Trees & Tree Traversals in C++: Complete Beginner's Guide

Software Developer & Computer Science Student

Published:
19 min read
Edit page
Table of Contents8 topics

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 O(n)O(n) 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:

  1. There is exactly one special node called the root.
  2. Every node except the root has exactly one parent.
  3. There are no cycles: from the root there is exactly one path to any node.

A tree with nn nodes always has exactly n−1n - 1 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) {}
};
  • data holds the value (an int here; it could be a string or any type).
  • left points to the root of the left subtree, or nullptr if there is none.
  • right points to the root of the right subtree, or nullptr if 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.

TermMeaningIn the diagram
RootThe only node with no parentA
ParentA node directly above another nodeB is the parent of E and F
ChildA node directly below another nodeE and F are children of B
SiblingNodes with the same parentE and F; also B, C and D
Leaf (external node)A node with no childrenC, E, F, G, I
Internal nodeA node with at least one childA, B, D, H
EdgeThe link between a parent and a childA–B
PathA sequence of nodes joined by edgesA → D → H → I
Depth of a nodeNumber of edges from the root down to that nodedepth(A) = 0, depth(I) = 3
Height of a nodeNumber of edges on the longest path from that node down to a leafheight(D) = 2, height(I) = 0
Height of the treeHeight of the root3
LevelAll nodes at the same depthlevel 1 = B, C, D
SubtreeA node together with all of its descendantsthe box around D, G, H, I
Degree of a nodeNumber of children of that nodedegree(A) = 3, degree(D) = 2
Degree of a treeThe largest degree of any node3

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:

WhereWhat the tree stores
File systemsFolders contain files and sub-folders
HTML / the DOM<html> contains <body>, which contains <div>s
CompilersExpressions become expression trees / syntax trees
DatabasesB-trees and B+ trees index millions of rows
std::map, std::setUsually a red-black tree (a self-balancing BST)
Priority queuesA binary heap, which is a complete binary tree stored in an array
NetworkingRouting tables, spanning trees
AI and gamesDecision trees, game trees (minimax)
CompressionHuffman 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 hh (in edges) and nn nodes:

  • Level ii has at most 2i2^i nodes (level 0 has 1, level 1 has 2, level 2 has 4, …).
  • The tree has at most 2h+1−12^{h+1} - 1 nodes.
  • The minimum possible height is ⌊log⁡2n⌋\lfloor \log_2 n \rfloor; the maximum is n−1n - 1 (a chain).
  • In any binary tree, if n0n_0 is the number of leaves and n2n_2 the number of nodes with two children, then n0=n2+1n_0 = n_2 + 1.
  • A tree with nn nodes has n−1n - 1 edges and n+1n + 1 nullptr child 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.

TypeRuleQuick test
Full (proper, strict)Every node has 0 or 2 childrenNo node has exactly one child
CompleteEvery level is completely filled except possibly the last, and the last level is filled from the leftLevel-order listing has no gap before the last node
PerfectAll internal nodes have 2 children and all leaves are at the same depthExactly 2h+1−12^{h+1} - 1 nodes
Balanced (height-balanced)At every node, the heights of the left and right subtrees differ by at most 1Used by AVL trees
Degenerate / skewedEvery internal node has exactly one childLooks like a linked list; height n−1n - 1

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 O(log⁡n)O(\log n) take O(n)O(n). 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 nn nodes can need about 2n2^n 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.

  1. Read the first value and make it the root. Push the root into the queue.
  2. 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:

TraversalOrderMnemonic
PreorderRoot, Left, Rightroot pre (before) the subtrees
InorderLeft, Root, Rightroot in between the subtrees
PostorderLeft, Right, Rootroot post (after) the subtrees
Level orderLevel 0, then level 1, then level 2, …, left to rightbreadth-first

The left subtree is always handled before the right subtree in all of them. All four results for our example tree:

TraversalOutput
Preorder1 2 4 5 7 3 6
Inorder4 2 7 5 1 3 6
Postorder4 7 5 2 6 3 1
Level order1 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.

1 2 3 4 5 6 7

Output
Interactive traversal of the example binary tree. Choose a traversal, then step through it or press Play.

Inorder Traversal (Left, Root, Right)

Rule: traverse the left subtree, visit the root, traverse the right subtree.

Step by step from the root:

  1. 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.
  2. Back at 2: its left subtree is done, so print 2. Then go right to 5.
  3. At 5: go left to 7. Print 7. Back at 5: print 5. 5 has no right child.
  4. 2’s subtree is finished. Back at 1: print 1, then go right to 3.
  5. 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.

  1. Print 1, then go left.
  2. Print 2, go left: print 4 (a leaf).
  3. Back at 2, go right: print 5, go left: print 7.
  4. 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.

  1. Go all the way left: print 4 (no children).
  2. Back at 2, its right subtree is 5. 5’s left subtree is 7: print 7. 5 has no right child: print 5.
  3. Both subtrees of 2 are done: print 2.
  4. Back at 1, go right to 3. No left child; right child 6: print 6. Then print 3.
  5. 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.

StepDequeue and printEnqueueQueue after (front → back)
start1[1]
112, 3[2, 3]
224, 5[3, 4, 5]
336[4, 5, 6]
44[5, 6]
557[6, 7]
66[7]
77[]

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 nn real calls plus n+1n + 1 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

OperationTimeExtra space
Preorder / inorder / postorder (recursive)O(n)O(n)O(h)O(h) call stack
Level order (queue)O(n)O(n)O(w)O(w), where ww is the widest level
Height, count nodes, count leavesO(n)O(n)O(h)O(h)
Build from level-order inputO(n)O(n)O(w)O(w) queue

Here nn is the number of nodes and hh the height. Each node is visited once, so time is O(n)O(n). The space is the recursion depth: O(log⁡n)O(\log n) for a balanced tree, but O(n)O(n) 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 n/2n/2 nodes, so level order’s queue can reach O(n)O(n).

Common Mistakes Beginners Make

  1. Missing the base case. Without if (root == nullptr) { return; } the function dereferences a null pointer and crashes on the first leaf.
  2. Uninitialised child pointers. Node* n = new Node; with no constructor leaves left and right as garbage. Always set them to nullptr.
  3. Confusing height and depth, or mixing the edge and node conventions in one answer. Say “height in edges” explicitly.
  4. Checking only the left child for a leaf. A leaf needs both left == nullptr and right == nullptr; node 3 in our tree has no left child but is not a leaf.
  5. Losing the root. Writing root = root->left; while building or traversing overwrites your only handle to the tree. Use a separate current pointer.
  6. Deleting the parent first. delete root; destroy(root->left); reads freed memory. Delete in postorder.
  7. 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.
  8. 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.

#ProblemSkill
1Binary Tree Inorder Traversal (LeetCode 94)Recursion template
2Binary Tree Preorder Traversal (LeetCode 144)Visit before recursing
3Binary Tree Postorder Traversal (LeetCode 145)Visit after recursing
4Binary Tree Level Order Traversal (LeetCode 102)Queue, level by level
5Maximum Depth of Binary Tree (LeetCode 104)Postorder-style return values
6Same Tree (LeetCode 100)Recursing on two trees at once
7Construct Binary Tree from Preorder and Inorder (LeetCode 105)Using traversal properties

Offline exercises, using the example tree from this article:

  1. Without running code, write the preorder of the tree after removing node 7. (Answer: 1 2 4 5 3 6.)
  2. Add a left child 8 to node 3. What are the new inorder and level order? (Answers: 4 2 7 5 1 8 3 6 and 1 2 3 4 5 8 6 7.)
  3. 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:

  1. Next: Binary Search Tree (BST) in C++: add an ordering rule and get fast search, insert and delete.
  2. Then test yourself with Tree Interview Questions.
  3. Preparing for a university exam? See Tree Questions for University Exams in Bangladesh.

Edit page
Share this post:

Related Articles

Continue exploring related topics and foundational concepts.


Previous Post
Binary Search Tree (BST) in C++: Search, Insert, Delete & Complete Guide
Next Post
Stack Using Array in C++: Fixed-Size Implementation, Overflow & Dry Run