Data Structures · Trees

Binary trees

Arrays, stacks, queues and linked lists are linear: each item has one item after it. A tree is hierarchical: one item can lead to several others, which lead to more. This page introduces the vocabulary of trees, shows how a binary tree is built from nodes and pointers in C++, and lets you build trees and watch the classic recursive algorithms run on them.

What is a tree?

A tree is a set of nodes connected by edges. One node, the root, is at the top. Every other node has exactly one parent, and a node can have any number of children. There are no loops: from the root there is exactly one path down to each node.

You already know trees: a family tree, a company org chart, the folders on your computer, the outline of an essay. Each is a hierarchy, where every item belongs to exactly one thing above it.

In a binary tree, every node has at most two children, called the left child and the right child. Left and right are different positions: a node with only a left child is a different tree from a node with only a right child.

An example binary tree. 8 is the root, with children 3 and 10. The leaves, the nodes with no children, are 1, 4, 7 and 13.

Vocabulary

TermMeaningIn the example
RootThe one node with no parent, at the top.8
Parent / childA node directly above / directly below another, joined by an edge.6 is the parent of 4 and 7
SiblingsNodes with the same parent.3 and 10
LeafA node with no children.1, 4, 7, 13
Internal nodeA node with at least one child.8, 3, 10, 6, 14
Ancestors / descendantsEvery node on the path up to the root / every node below.Ancestors of 7: 6, 3, 8
SubtreeA node together with all of its descendants. Every node is the root of its own subtree.3, 1, 6, 4, 7
Depth (level)The number of edges from the root down to the node. The root has depth 0.depth of 6 is 2
HeightThe number of edges on the longest path from a node down to a leaf. A leaf has height 0, and an empty tree has height −1.height of the tree is 3
SizeThe number of nodes.9
Stop and think
A tree has 9 nodes. How many edges does it have? Does that depend on its shape?

8. Every node except the root has exactly one edge going up to its parent, so a tree with n nodes always has n − 1 edges, whatever its shape.

Could a node in a tree have two parents?

No. If it did, there would be two different paths from the root to it, and that would make a cycle in the drawing. Structures that allow it are called graphs (or DAGs if the edges have a direction), which you met with topological sort.

A binary tree in C++

Each node holds three things: its data, a pointer to its left child, and a pointer to its right child. A missing child is a nullptr. The whole tree is reached through one pointer to the root.

struct Node {
    int data;
    Node* left;     // nullptr if there is no left child
    Node* right;    // nullptr if there is no right child

    Node(int value) : data(value), left(nullptr), right(nullptr) {}
};

// Building the top of the example tree by hand:
Node* root = new Node(8);
root->left = new Node(3);
root->right = new Node(10);
root->left->left = new Node(1);

A class with public members works the same way. This is the same idea as a linked list node, except that each node has two "next" pointers instead of one.

What is really in memory. Each node is a box with a value and two pointers. Arrows are pointers; ∅ is nullptr.
Stop and think
Why does a Node hold a pointer to its children (Node* left) instead of a whole child node (Node left)?

A Node that contained a whole Node would contain another whole Node inside that, and so on forever, so it would have infinite size; C++ will not compile it. A pointer is a fixed size and can also be nullptr, which is how we say "no child here."

Explore a tree

Build your own binary tree. Click a node to select it: its subtree is shaded, its path to the root is outlined, and the facts on the right describe it. Use the buttons to add children, change values, or remove a subtree.

Presets

Selected node

Whole tree

Shapes of binary trees

The explorer labels a tree with these shape names when they apply. Try the presets, then try to build each one yourself.

Full: every node has 0 or 2 children, never exactly 1.
Complete: every level is full except possibly the last, which is filled from the left. Heaps have this shape.
Perfect: every internal node has 2 children and all leaves are at the same depth.
Degenerate (skewed): every node has at most one child. It is really a linked list.
Stop and think
What is the largest number of nodes a binary tree of height h can have? Check it with the Perfect preset.

A perfect tree: 1 + 2 + 4 + … + 2h = 2h+1 − 1 nodes. Height 3 gives 15.

With n nodes, what is the smallest possible height, and what is the largest?

The smallest is about log₂ n (exactly ⌊log₂ n⌋), when the tree is as bushy as possible. The largest is n − 1, when it is skewed into a single chain. This gap is why balanced trees matter: searching a path costs O(height), which can be O(log n) or O(n).

Traversals and recursive algorithms

A traversal visits every node once. Because a tree is defined recursively (a node, plus a left subtree, plus a right subtree), the natural traversals are recursive too. They differ only in when the node itself is visited:

Height and size follow the same pattern: ask each subtree for its answer, then combine the two answers at the node.

The tree (the one you built above)

Output

Call stack

    What is happening

    BinaryTree.cpp

      Stop and think
      Before you press Run on the example tree, write down its preorder, inorder and postorder. Then check.

      Preorder 8 3 1 6 4 7 10 14 13. Inorder 1 3 4 6 7 8 10 13 14. Postorder 1 4 7 6 3 13 14 10 8. Notice that the inorder comes out sorted; the example happens to be a binary search tree, which is coming up next.

      To delete every node of a tree (to free its memory), which traversal should you use, and why?

      Postorder. A node may only be deleted after both of its subtrees are deleted, because once it is gone you can no longer reach its children through it.

      To make a copy of a tree, which traversal is natural?

      Preorder: create the copy of a node first, then copy its left and right subtrees and attach them to it.

      Can you rebuild a tree if you only know its preorder sequence?

      No: different shapes can share a preorder (for example 1 with a left child 2, and 1 with a right child 2 both give "1 2"). With both the preorder and the inorder of a tree with distinct values, the tree is unique: the preorder tells you the root, and the inorder tells you which values are in its left and right subtrees.

      Why does level order use a queue, while the other traversals use recursion (a stack)?

      Level order must finish all nodes at depth d before any at depth d + 1. A queue is first-in, first-out, so children wait behind everything already on the current level. Recursion goes as deep as it can first, which is depth-first order.

      How long does any of these traversals take, in big-O?

      O(n): each node is visited once and does a constant amount of work. The extra memory is O(height) for the recursion stack, or up to O(width) for the level-order queue.

      Where binary trees are used

      Binary search treesKeep values in order so that search, insert and delete follow one path from the root: O(log n) when the tree is balanced.
      Heaps and priority queuesA complete binary tree stored in an array. The highest-priority item is always at the root, so peek is O(1) and insert or remove is O(log n).
      Expression treesOperators are internal nodes and numbers are leaves. A postorder traversal evaluates the expression; compilers build these syntax trees from code.
      Huffman codingA tree of characters built from their frequencies. Left and right edges spell out each character's bit code for compression.
      Decision treesEach internal node asks a yes/no question and each leaf is a decision, as in game AI and machine learning.
      Space partitioningk-d trees split space in two at every node, to find nearby points quickly in maps and graphics.
      Stop and think
      A heap is a binary tree, but it is usually stored in an array, not with pointers. Why does that work for a heap but not for a general binary tree?

      A heap is always complete, so its nodes fill the array with no gaps and the children of index i are always at 2i + 1 and 2i + 2. A general tree can have missing children anywhere; storing it in an array would leave holes, and a skewed tree of height h would need about 2h+1 slots for only h + 1 nodes.

      Draw the expression tree for (3 + 4) × 5. What do preorder, inorder and postorder give?

      × at the root, with + (children 3 and 4) on the left and 5 on the right. Preorder: × + 3 4 5 (prefix notation). Inorder: 3 + 4 × 5, which needs parentheses to mean the right thing. Postorder: 3 4 + 5 × (postfix, which a stack can evaluate directly).