What is a Binary Tree
A binary tree is a tree where every node has at most two children. That is the only change from the previous article: one number, changed from "any" to "two".
It buys more than it looks like. The two children get names, left and right, and because they are named they are no longer interchangeable: a node with only a left child is a different tree from a node with only a right child, even though both have one child. Every later article in this series builds on that asymmetry.
The either/or analogy
Every twenty questions game is a binary tree. "Is it bigger than a car?" splits everything you might be thinking of into two groups, and the answer picks one. The next question splits that group again.
The game works in twenty questions for the same reason binary trees matter: each answer discards half of what is left, and twenty halvings cover a million possibilities. The number of halvings you get before you run out of tree is the height, and most of this article is about it.
node 2 has both children; node 3 has only a right child, which is a different tree from having only a left one
The problem a general Tree couldn't solve
The general tree from the previous article can hold any hierarchy, and that flexibility costs it two things.
You cannot reason about its height. A tree with 100 nodes might have height 1 (a root with 99 children) or height 99. Knowing the node count tells you nothing about how far you might have to walk, and the height is the cost of every operation. Cap the children at two and the two numbers become linked: n nodes in a tidy binary tree means height about log₂ n, and the rest of this series depends on that relationship.
You cannot put it in an array. A node with a variable number of children needs a slice per node, which means a separate heap allocation per node and pointer chasing to reach any of them. Fix the count at two and the positions become computable: a child's index is arithmetic on its parent's, so the whole tree collapses into one flat block of memory with no pointers at all. That trick is what makes the heap in the last article of this series fast, and it only works because of the two.
So the two-child limit makes both the height and the memory layout predictable.
The shapes a Binary Tree can take
Most of the vocabulary around binary trees describes their shape, and the terms overlap in ways that trip people up, so it pays to be precise. Every definition below answers the same question: where are the nodes allowed to be missing?
Full
A full binary tree is one where every node has either zero or two children, never exactly one.
node 2 is a leaf, node 3 has both, and nothing in between
This says nothing about where the leaves sit. A full tree can be wildly lopsided; it just cannot have a node with a lonely single child.
Complete
A complete binary tree has every level filled except possibly the last, and the last level fills from the left with no gaps.
six nodes, no gap before the end; node 3 has one child, so this is not full
This is the shape that matters most in practice, because it is exactly the shape that fits an array with no wasted slots. The array representation below comes back to it.
Perfect
A perfect binary tree has every level completely filled. There are no gaps anywhere, which forces a very specific node count: a perfect tree of height h has exactly 2^(h+1) − 1 nodes.
height 2, so 2³ − 1 = 7 nodes, and no other count is possible
Perfect is the strongest of the three: a perfect tree is automatically complete and automatically full. The reverse fails in both directions, as the next section shows.
Balanced, and unbalanced
Balanced is the odd one out, because it is a condition on height instead of on where nodes sit. A tree is balanced when, for every node, its two subtrees differ in height by at most one.
every node has zero children or two, so this is full; node 1's subtrees differ in height by 2, so it is not balanced
That figure answers the most common mistake with this vocabulary: full does not mean balanced. Every node there has zero children or two, and the tree is still visibly lopsided, because shape rules and height rules measure different things.
Unbalanced just means the balanced condition fails. As the next two articles show, a search tree ends up that way by accident when data arrives in order.
Degenerate
A degenerate binary tree has exactly one child per internal node. Every level holds one node.
four nodes, height 3: a linked list wearing a tree's type
This is the worst case, and it happens in practice. It has height n − 1 instead of log₂ n, so every operation that was supposed to be logarithmic is linear, and the left/right fields are pure overhead over a plain linked list.
How the shapes overlap
The five terms don't form a ladder from weakest to strongest, and many explanations draw them as one. Here is how they actually relate:
- Perfect implies complete, full and balanced. All three, always. It is the strictest shape.
- Complete implies balanced, but says nothing about full: the complete figure above has a node with one child.
- Full says nothing about complete, and nothing about balanced. The full figure above has a gap in the middle; the unbalanced figure above is full and lopsided.
- Full and complete are independent in both directions. There are trees that are full and not complete, and trees that are complete and not full. Neither implies the other.
- Degenerate implies unbalanced, as soon as the tree is tall enough to have a lopsided subtree.
Height against node count
Everything above leads to one number. The height of a binary tree is what every operation costs, because the longest root-to-leaf path is the most work a search can be forced to do.
For a given node count n, the height depends entirely on shape, and the spread between the best and worst cases is enormous:
| Shape | Height for n nodes | At n = 1,000,000 |
|---|---|---|
| Perfect | log₂(n+1) − 1 | 19 |
| Complete | ⌊log₂ n⌋ | 19 |
| Degenerate | n − 1 | 999,999 |
That is the same million nodes, and a walk of 19 steps against a walk of a million. The two heights grow at different rates, so no constant factor closes the gap.
- O(log n)
- O(n)
The good case is logarithmic for a reason that comes up in every remaining article. Each level of a binary tree holds at most twice the level above it: 1, 2, 4, 8, 16. So a tree of height h holds at most 2^(h+1) − 1 nodes, and reading that backwards, n nodes need a height of at least log₂ n. Doubling your data adds one level.
Representing a Binary Tree in memory
Two children, two representations.
Linked nodes
The direct one: a struct with a value and two pointers. This is the linked-list node from earlier in the series with a second pointer bolted on, and everything about it should feel familiar.
package mainimport "fmt"func main() { // The perfect tree from the figure above. root := &Node{ Value: 1, Left: &Node{ Value: 2, Left: &Node{Value: 4}, Right: &Node{Value: 5}, }, Right: &Node{ Value: 3, Left: &Node{Value: 6}, Right: &Node{Value: 7}, }, } fmt.Println(root.Count()) // 7 fmt.Println(root.Height()) // 2 fmt.Println(root.IsBalanced()) // true}package maintype Node struct { Value int Left, Right *Node}// A nil receiver is a valid empty tree, which is what removes the// nil checks from every caller — `n.Left.Height()` is safe even// when Left is nil.func (n *Node) Count() int { if n == nil { return 0 } return 1 + n.Left.Count() + n.Right.Count()}// -1 for the empty tree, so a leaf is 0 without a special case.func (n *Node) Height() int { if n == nil { return -1 } return 1 + max(n.Left.Height(), n.Right.Height())}func (n *Node) IsBalanced() bool { if n == nil { return true } gap := n.Left.Height() - n.Right.Height() if gap < -1 || gap > 1 { return false } return n.Left.IsBalanced() && n.Right.IsBalanced()}The trick worth stealing there is the nil receiver. In Go a method can be called on a nil pointer, so defining Height() to return -1 for the empty tree means no caller ever checks for nil. The base case lives in one place instead of at every call site.
The array representation
The other representation drops the pointers entirely. Number the nodes level by level, left to right, starting at 0, and store them in a flat slice at those indices. The relationships become arithmetic:
left := 2*i + 1right := 2*i + 2parent := (i - 1) / 2There is no Left field, no Right field and no allocation per node. The tree is one contiguous block, and a child's address is computed from its parent's with a shift and an add.
node 1's children are at 2·1+1 = 3 and 2·1+2 = 4 · node 5's parent is at (5−1)/2 = 2
You get no pointer chasing and no per-node allocation, and siblings sit next to each other in memory, so walking a level is a sequential read, which is what the CPU cache is built for. That is the opposite of the cache-hostile pointer chasing the linked-list article warned about.
The downside is that a node's index comes from its position in the tree, not from insertion order, so a missing node still consumes its slot. That makes the cost of this representation depend entirely on shape:
- On a complete tree it is free. The filled slots are exactly
0 .. n−1, contiguous, with nothing wasted, which is why "complete" has a name of its own. - On a degenerate tree it is catastrophic. Height
n − 1means the deepest node's index is around2^n, so 21 nodes in a right-leaning chain need over two million slots.
Try it yourself
Build a tree by clicking and watch the classifications update as you go. Click any shape the tree fails to see which node ruled it out.
click a dashed slot to add a node, a solid one to remove it and its subtree · the array below works too
Keyboard and mouse
- M
- sound on or off
- F
- fullscreen
- R
- reset
- Space+drag
- move the canvas
- Ctrl+scroll
- zoom
Try loading full and checking whether it is complete, then load complete and check whether it is full. Neither implies the other, and seeing it by hand is more convincing than the paragraph above.
Common operations and their costs
The same operations, on the same node count, in the best shape and the worst:
| Operation | Complete tree | Degenerate tree |
|---|---|---|
| Reach the deepest node | ||
| Find a value | ||
| Count nodes, measure height | ||
| Array slots needed |
Read the first row and the last one together. The shape leaves what a binary tree can do unchanged and changes what it costs, by an unbounded factor.
Finding a value is still O(n) in both columns. Nothing in this article tells you which way to go at a node, so a search still has to consider everything. The next article closes that gap.
Binary Trees in the real world
Expression and parse trees. Every binary operator is a node whose two children are its operands. 2 * (3 + 4) is a * node whose children are 2 and a + node. Compilers and calculators build these, and evaluating one means resolving children before parents. The two-child shape comes straight from the operators being binary.
Huffman coding. The compression behind ZIP and JPEG builds a binary tree where every left branch is a 0 bit and every right branch a 1. A character's code is its path from the root, so the tree itself is the codebook, and frequent characters are placed shallow to get short codes.
Heaps and priority queues. A heap uses the array representation above, and schedulers, event loops and timers are almost always backed by one. The heap gets its own article at the end of the series.
Binary space partitioning. Games and renderers split space in half repeatedly: each node is a region and its two children are the halves. Doom famously used a BSP tree to decide draw order, and collision detection and ray tracing use the same idea.
Merkle trees. Git commits, blockchain blocks and rsync all hash pairs of nodes upward, so a single root hash certifies an entire dataset and a mismatch can be localised in log n comparisons. Here the tree is used for verification and has nothing to do with searching.
When Binary Trees fall short
Two children is often the wrong number. A filesystem directory holds many entries, and a DOM element wraps many children. Forcing those into a binary tree means either the first-child/next-sibling trick from the previous article or a lot of pretending. Use the shape that matches your data.
Nothing keeps the tree short. Every good property in this article assumed a tidy shape, and the definition guarantees none of it. This is the biggest caveat, and the next two articles deal with it: first by watching a search tree degenerate from ordinary input, then by fixing it.
The array representation only pays off when complete. On a complete tree it is the fastest layout available. On a tree whose shape you do not control, it turns a memory optimisation into exponential waste.
Still no ordering. A binary tree constrains where nodes can be, not which values go where. Search is O(n) in the best shape and the worst. The structure is now predictable, but it is not yet useful for lookup.
Pointer chasing, unless you flattened it. In the linked representation each node is its own allocation, so a walk is a sequence of potential cache misses. That is the same cost the linked-list article described, and the reason the array representation exists at all.
Summary
Binary trees take the general tree and cap the children at two, which makes it predictable:
- At most two children, and they are named:
leftandrightare not interchangeable, and later articles build on that asymmetry - Full, complete, perfect, balanced, degenerate: full and complete constrain different things and imply nothing about each other; perfect implies all three
- Balanced is a height rule, not a shape rule: a full tree can be badly unbalanced, which is the intuition most people get wrong
- Height is the cost:
log₂ nin a tidy tree againstn − 1in a degenerate one, which is 19 steps against a million at the same node count - A complete tree fits an array exactly:
2i+1,2i+2,(i−1)/2, no pointers and no waste, and exponential waste on any other shape - Search is still O(n): the shape is constrained, the values are not
The two-child limit makes height a function of node count and makes a child's address computable from its parent's. Neither of those tells you where a value lives, so searching a binary tree still means checking every node.