Sub topic 1
Complete Binary Trees: The Shape Behind a Heap
Heap sort needs a tree, but it never allocates a single tree node. It works on a plain array and treats that array as a tree. This only works because the tree has one particular shape, the complete binary tree. This chapter covers that shape: what it is, what it guarantees, and why heap sort depends on those guarantees. The next chapter turns the shape into index arithmetic.
Prerequisites
This chapter assumes you are comfortable with:
- Basic Python: functions, loops, classes, and lists.
- Zero-based indexing in arrays.
- Big-O notation, especially O(log n) and O(n).
- Binary trees as a concept: nodes, a root, left and right children, leaves, and parent-child edges.
You do not need any prior knowledge of heaps or priority queues.
What "Complete" Means
A binary tree is complete when two conditions hold:
- Every level except possibly the last is completely filled.
- The nodes on the last level sit as far left as possible, with no gaps between them.
Level 0 holds the root. Level 1 holds up to 2 nodes, level 2 up to 4, and level k up to 2^k. In a complete tree you could fill the levels by writing nodes in reading order: top to bottom, and left to right within each level. You stop when you run out of nodes. Whatever shape you end up with is the complete tree for that node count.
In this tree, node 8 has a left child and no right child. That is allowed because the missing slot is the rightmost position on the last level. If 6 hung off 8's right side instead, the left slot would be a gap and the tree would not be complete.
Complete, Perfect, and Full Are Different Shapes
Textbooks use similar words for different shapes, and some older sources swap them. This tutorial uses the following definitions:
| Term | Definition | Example with 6 nodes possible? |
|---|---|---|
| Perfect | Every level is completely filled; all leaves on the same level | No (perfect trees have 1, 3, 7, 15, ... nodes) |
| Complete | All levels full except the last, which is filled left to right | Yes, exactly one shape |
| Full (or proper) | Every node has 0 or 2 children | No (full trees always have an odd node count) |
Every perfect tree is complete. A complete tree can also be full, as the 7-node perfect tree is, but completeness does not require it. The 6-node tree above is complete but not full, because node 8 has exactly one child.
Why a Heap Needs This Shape
A heap combines two requirements: a shape rule (the tree is complete) and an ordering rule (the max-heap property, covered two chapters from now). The shape rule brings three properties that heap sort relies on.
1. Exactly One Shape per Node Count
Once you fix the node count n, the complete tree has exactly one possible shape. Positions get filled in reading order, so there is never a choice about where the next node goes. This means the shape carries no information of its own. Only the values stored in it matter, so you can drop the pointers and keep just the values in order.
2. No Gaps in Reading Order
If you list a complete tree's nodes in reading order, every position from the first to the n-th is occupied. A list with no holes is exactly what an array is. The next chapter shows that this lets you find any node's parent and children with simple arithmetic on its position, so the tree needs no pointer fields at all.
3. Logarithmic Height
The height of a tree is the number of edges on the longest path from the root to a leaf. A complete tree with n ≥ 1 nodes has height ⌊log₂ n⌋. Every heap operation in this tutorial walks at most one root-to-leaf path, so this bound is what keeps each operation at O(log n) and heap sort at O(n log n).
Compare this with an unrestricted binary tree. Five nodes can form a chain in which each node has only a left child. That chain has height 4 instead of 2, and a chain of n nodes has height n − 1. Completeness rules out that worst case.
Counting Levels, Nodes, and Leaves
Some counting facts come up repeatedly in later chapters, especially in the proof that building a heap takes linear time.
- Level k holds at most 2^k nodes.
- A perfect tree of height h holds 2^(h+1) − 1 nodes.
- A complete tree of height h holds between 2^h nodes (one node on the last level) and 2^(h+1) − 1 nodes (last level full).
- Solving 2^h ≤ n < 2^(h+1) for h gives h = ⌊log₂ n⌋.
- A complete tree with n nodes has ⌈n/2⌉ leaves and ⌊n/2⌋ internal (non-leaf) nodes.
The last fact matters a lot. Half the nodes in a heap are leaves, and a leaf already satisfies any ordering rule because it has no children. The bottom-up construction algorithm skips them entirely and starts work at the last internal node.
The code below computes these quantities from n alone. That it can do so shows that the shape is fully determined by the node count.
def height(n):
"""Height in edges of the complete binary tree with n nodes."""
if n < 1:
raise ValueError("a tree with no nodes has no height")
return n.bit_length() - 1 # equals floor(log2(n)) for n >= 1
def level_sizes(n):
"""Number of nodes on each level, from the root down."""
sizes = []
k = 0
remaining = n
while remaining > 0:
size = min(2 ** k, remaining)
sizes.append(size)
remaining -= size
k += 1
return sizes
def leaf_count(n):
return n - n // 2 # ceil(n / 2)
for n in [1, 2, 6, 7, 10]:
print(n, height(n), level_sizes(n), leaf_count(n))Running it prints:
1 0 [1] 1
2 1 [1, 1] 1
6 2 [1, 2, 3] 3
7 2 [1, 2, 4] 4
10 3 [1, 2, 4, 3] 5Using n.bit_length() - 1 instead of math.floor(math.log2(n)) avoids floating-point rounding. For very large integers, log2 can return a value just below an exact power of two, and the floor then comes out one too small.
Checking Whether a Linked Tree Is Complete
A heap stored in an array is complete automatically, because an array has no holes. A tree built from linked nodes can break the rule, though. Checking a linked tree is good practice for the definition. Do a breadth-first traversal, which visits nodes in reading order, and enqueue missing children as None. The tree is complete exactly when no real node shows up after the first None.
from collections import deque
class Node:
def __init__(self, value, left=None, right=None):
self.value = value
self.left = left
self.right = right
def is_complete(root):
if root is None:
return True
queue = deque([root])
seen_gap = False
while queue:
node = queue.popleft()
if node is None:
seen_gap = True
continue
if seen_gap:
return False # a real node after a gap
queue.append(node.left)
queue.append(node.right)
return True
good = Node(9, Node(7, Node(3), Node(5)), Node(8, Node(6)))
gap = Node(9, Node(7, Node(3), Node(5)), Node(8, None, Node(6)))
chain = Node(1, Node(2, Node(3)))
print(is_complete(good)) # True
print(is_complete(gap)) # False
print(is_complete(chain)) # FalseThe gap tree fails because the traversal sees 9, 7, 8, 3, 5, then None for 8's missing left child, then 6. The chain tree fails because 2's missing right sibling comes before 3 in reading order.
How the Shape Changes During Heap Sort
Heap sort keeps the tree complete at every step. To do that, it only ever changes the shape at one spot: the last position in reading order, which is the rightmost node on the bottom level.
- Removing a node: heap sort swaps the root's value into the last position and then shrinks the heap by one, detaching that position. A complete tree with its last node removed is still complete.
- Adding a node, which priority queues do: the new node goes into the next free slot in reading order. A complete tree with a node added there is still complete.
Removing any other node, such as the root itself, would leave a hole. Heap operations never remove a node from the middle. They move values around inside a fixed shape and change the shape only at the end.
Common Mistakes
- Counting height in levels instead of edges. A single node has height 0 in this tutorial. If you count levels, every bound shifts by one. Pick one convention and keep it.
- Filling the last level from the right. The last level must be packed to the left. A node whose only child is a right child always breaks completeness.
- Assuming n must be a power of two minus one. That describes a perfect tree. A complete tree can have any n ≥ 0.
- Using floating-point log for height. Prefer integer methods such as
bit_lengthfor exact results.
Exercise
Draw or describe the complete binary tree with 10 nodes. How many nodes are on each level, what is its height, and how many leaves does it have?
Show answer
Levels hold 1, 2, 4, and 3 nodes. The height is floor(log2 10) = 3. The leaves are the 3 nodes on level 3 plus the 2 rightmost nodes on level 2, which have no children, for 5 leaves in total, matching ceil(10/2) = 5.
Exercise
A tree has root A with children B and C. B has no children. C has a left child D. Is this tree complete? Explain using reading order.
Show answer
No. In reading order the positions are A, B, C, B's left, B's right, C's left. B's two child slots are empty, but D sits in C's left slot after them. A real node appears after a gap, so the tree is not complete.
Exercise
What is the minimum and maximum number of nodes in a complete binary tree of height 4?
Show answer
The minimum is 2^4 = 16 (levels 0 to 3 full, with one node on level 4). The maximum is 2^5 - 1 = 31 (a perfect tree).
Exercise
Why does heap sort remove the last node in reading order rather than the root node when it shrinks the heap?
Show answer
Detaching the last node leaves a complete tree, while removing the root or any other interior node would leave a gap. Heap sort therefore moves the root's value into the last position and detaches that position, so the shape stays complete and can still be stored in a contiguous array prefix.