TL;DR
A binary tree is a set of nodes arranged in a hierarchy. Each node holds a value and has at most two children, called left and right. There is exactly one top node, the root. A binary search tree adds one rule: everything smaller than a node sits in its left subtree, and everything larger sits in its right subtree. That rule lets you find, insert or delete a value by walking down a single path instead of scanning every value.
The shape of the tree decides how long that walk is. A balanced tree with nodes has height about , so a lookup takes only a few steps even among millions of values. A tree built from keys that arrive in sorted order degenerates into a chain, and the same lookup then takes steps.
Where you'll see it: in the ordered map and set types of standard libraries (C++ std::map is commonly a red-black tree), in the expression trees that compilers build from source code, in the tree-shaped softmax over a binary tree used in machine learning, and in the B-tree relatives that index most databases.
Intuition
A family tree with two slots
Picture a family tree in which every person has room for exactly two children, one on the left and one on the right. The oldest ancestor is the root. People with no children are the leaves. The depth of a node is how many steps down it sits from the root, and the height of the whole tree is the depth of its deepest node. Those words come back throughout this lesson.
Why limit each node to two? Two is the smallest number that lets you make a real choice at each step. A single child is just a list, which can only be walked one way. With two children, every comparison in a balanced tree throws away about half of the remaining possibilities. That halving is why binary trees are everywhere in searching.
The ordering rule
Now add one rule. Pick any node with key 5. Every key in its left subtree is below 5, and every key in its right subtree is above 5. A binary tree with this rule is a binary search tree. To look up 9, you compare with the root. If 9 is smaller, you go left and never look at the right side at all. If it is larger, you go right and ignore the left side. Each comparison takes you one level down.
It is like a library where each shelf card tells you which half of the room to walk into. You never read every book. You read a handful of cards.
- balanced tree: about log2 n steps
- chain: n steps
Why shape matters
Insert the keys 1, 2, 3, 4, 5 into an empty binary search tree, in that order. Each new key is larger than everything already there, so it always goes right. The result is a chain five levels tall. Now insert 3, 1, 4, 2, 5 instead. The tree has three levels. The keys are the same and the operations are the same; only the shape changed. Shape is the thing to watch.
The math
Definition
A binary tree is either empty, or a root node with a value and two binary trees, called its left subtree and right subtree, either of which may be empty. Every node therefore has at most two children.
This definition refers to smaller binary trees inside itself, so it is recursive. That is why Recursion is the natural way to write code that processes trees: one rule handles every subtree.
Height and depth. The depth of a node is the number of edges on the path from the root to it. The root has depth 0. The height of a tree is the largest depth of any node. A single node has height 0. By convention the empty tree has height .
How many nodes fit in a given height. Depth can hold at most nodes, since each node has at most two children. A tree of height therefore holds at most
nodes. The sum is a geometric series, so the last step is the standard formula with .
Turn this around. If a tree has nodes, then . Taking base-2 logarithms gives , so . No binary tree with nodes can be shorter than levels. A tree is called balanced when its height is , which is the best possible.
Searching. A binary search tree is valid when, for every node, every key in its left subtree is smaller and every key in its right subtree is larger. Searching, inserting and deleting all follow one path from the root, so each costs (see Big-O Notation). For a balanced tree that is . For a chain it is , and the chain is the failure case the rest of this lesson keeps returning to.
- Start at the root.
- If the current node is empty, the key is not in the tree. Stop.
- If the key equals the node's value, the search succeeds. Stop.
- If the key is smaller than the node's value, move to the left child. Otherwise move to the right child.
- Go to step 2.
Traversals. There are three depth-first orders. Preorder visits the node, then its left subtree, then its right subtree. Inorder visits the left subtree, then the node, then the right subtree. Postorder visits left, right, then the node. Level-order visits nodes one depth at a time, usually with a queue. Each visits every node once, so each costs .
The inorder traversal of a binary search tree outputs its keys in sorted order. That is why a sorted list can be read out of a tree in linear time.
Array form of a complete tree. A complete tree fills every level except possibly the last, which fills from the left. Such a tree can be stored in an array with no pointers at all. Using 0-based indices, the children of index sit at and , and the parent of index sits at . This is the layout a binary heap uses.
Worked examples
Take the tree T with root 4, left child 2 (whose children are 1 and 3), and right child 6 (whose children are 5 and 7).
- Inorder: left subtree, root, right subtree. The left subtree gives 1, 2, 3. Then 4. The right subtree gives 5, 6, 7. Result: 1, 2, 3, 4, 5, 6, 7.
- Preorder: root first. The left subtree in preorder is 2, 1, 3, and the right subtree is 6, 5, 7. Result: 4, 2, 1, 3, 6, 5, 7.
- Postorder: root last. The left subtree gives 1, 3, 2, the right gives 5, 7, 6. Result: 1, 3, 2, 5, 7, 6, 4.
- Level-order: depth 0 gives 4, depth 1 gives 2 and 6, depth 2 gives 1, 3, 5, 7. Result: 4, 2, 6, 1, 3, 5, 7.
Interpretation: inorder reads the keys in sorted order, because T is a binary search tree. The other orders show the same nodes in a different sequence, which matters when you copy or delete a tree.
Use the tree T from the previous example. Search for 5.
- Compare with the root 4. Since 5 is larger than 4, go right to 6.
- Compare with 6. Since 5 is smaller than 6, go left to 5.
- Compare with 5. Found.
That is 3 comparisons, and the tree has 7 nodes, so the bound edges, that is 3 levels, is met exactly.
Now search for 8.
- Compare with 4. 8 is larger, go right to 6.
- Compare with 6. 8 is larger, go right. The right child of 6 is empty.
- Stop. Not found.
Interpretation: a miss costs one comparison per level just like a hit, so the cost is set by the height, not by where the key is.
Tradeoffs and failure modes
A plain binary search tree is simple, but its speed depends entirely on its shape. Insert keys in sorted order and you get the worst case.
| Situation | What goes wrong | Better choice |
|---|---|---|
| Keys arrive in sorted or nearly sorted order | The tree becomes a chain, so lookups cost | A self-balancing tree such as an AVL tree or a red-black tree |
| You only ever need the smallest or largest item | A full ordered tree does more work than needed | A binary heap, with removal and peek |
| Data is too big for memory or lives on disk | One node per pointer means many random reads | A B-tree with many keys per node |
| You need exact-match lookup and never need order | Tree bookkeeping costs time and space | A hash table, usually on average |
| The data is static and sorted | Pointers cost memory for nothing | A sorted array with binary search |
Other failure modes are worth knowing. Deleting a node that has two children needs care: replace it with its inorder successor, the smallest key in its right subtree. A recursive traversal of a very deep tree uses one call-stack frame per level, so a chain of a million nodes can overflow the stack. Trees also scatter their nodes across memory, so each step can be a cache miss. An array-based heap avoids most of that.
History
Trees were first studied as mathematical objects. In the 1850s, Arthur Cayley counted tree-shaped structures while working on chemical compounds, and his work set up the enumeration of trees that computer scientists still use.
Binary trees became a data structure in the late 1950s and early 1960s, as programmers needed fast ways to keep data sorted in memory. Thomas Hibbard published an analysis of binary search trees, including deletion, in 1962. In the same year, Georgy Adelson-Velsky and Evgenii Landis published the AVL tree, the first self-balancing binary search tree. It guarantees that the two subtrees of any node differ in height by at most one, so lookups stay logarithmic even under adversarial insertion orders.
David Huffman's 1952 method for minimum-redundancy codes built a binary tree from symbol frequencies, and that tree is still how Huffman coding assigns bit patterns to characters. Later, Rudolf Bayer introduced the symmetric binary B-tree in 1972, and Leo Guibas and Robert Sedgewick presented the red-black tree in 1978. Both are self-balancing binary trees and are now standard in libraries and databases. Donald Knuth analysed these structures at length in The Art of Computer Programming, Volume 3, which is still the reference most people cite.
Check yourself
QuestionRecall: what two properties make a binary tree a binary search tree?Show answer
Every node has at most two children, which is true of every binary tree. The search-tree property is that, for each node, every key in its left subtree is smaller than the node's key and every key in its right subtree is larger. This ordering is what lets a lookup skip an entire subtree after one comparison.
QuestionComputation: what is the maximum number of nodes in a binary tree of height 4?Show answer
The formula gives . Check it level by level: depth 0 holds 1 node, depth 1 holds 2, depth 2 holds 4, depth 3 holds 8 and depth 4 holds 16. The total is . A tree of height 4 has five levels, not four, because height counts edges from the root.
QuestionWhy: why does the inorder traversal of a binary search tree produce keys in sorted order?Show answer
Inorder visits the left subtree, then the node, then the right subtree. By the search-tree property, every key in the left subtree is smaller than the node, and every key in the right subtree is larger. Applying this recursively, everything output before a node is smaller than it, and everything output after it is larger. So the output is in ascending order, and it takes time because each node is visited once.
QuestionApplied: a logging system appends records with timestamps that only ever increase, and it must support lookup by timestamp. Is a plain binary search tree a good choice?Show answer
No. Because each new timestamp is larger than all previous ones, a plain binary search tree becomes a chain, and lookups cost . Use a self-balancing tree such as a red-black tree, which keeps lookups at for the same insertion order. For data that lives on disk, a B-tree is usually better still, since each node holds many keys and each disk read covers a whole node.
Sources
- Binary tree (Wikipedia)
- Binary search tree (Wikipedia)
- AVL tree (Wikipedia)
- Donald Knuth, The Art of Computer Programming, Vol. 3: Sorting and Searching