Balance: why a lopsided tree becomes a linked list
🌍 In real life. A teacher puts the class's roll numbers into a binary search tree, reading them off the register in order: 1, 2, 3, 4, … Each new number is bigger than everything before it, so it always goes right, right, right to the bottom. The tree ends up as one long line, no better than a linked list (Chapter 41): finding roll number 40 means walking past all 39 before it.
The same values in a different order, starting from the middle of the class, give a short, bushy tree where any number is a few steps away. A BST is only as fast as it is balanced.
The idea in one sentence: a BST's shape depends on the order its values arrive in, and searches cost one comparison per level, so a tree is fast only when it is balanced: at every node, the two subtrees' heights differ by at most 1.
Its words:
- balanced: at every node, the left and right subtrees' heights differ by at most 1; then the height is O(log n), at most about 1.44 × log₂ n
- degenerate tree: a tree where every node has at most one child: a chain, height n
- self-balancing tree: a BST that repairs its shape after each insert and delete, such as an AVL tree or a red-black tree
- rotation: the repair move: a child is lifted above its parent and one subtree changes sides, so the inorder order stays the same while the heights even out
How it goes wrong, step by step:
- insert 1: it is the root
- insert 2: bigger than 1, so it goes to 1's right
- insert 3: bigger than 1 and 2, so it goes right twice
- each new value goes one level deeper: n sorted values make n levels
Watch the search for 5 in the tree built from 1, 2, 3, 4, 5, 6 in order. The counter shows 6 levels for 6 nodes:
The same six values, inserted middle first (4, 2, 6, 1, 3, 5), make a tree of only 3 levels, and the same search needs 3 comparisons instead of 5:
Why balance gives O(log n). In a balanced tree no branch can run far deeper than the others. Each level can hold twice as many nodes as the one above (h full levels hold 2ʰ − 1, Lesson 47.1), and the balance rule stops the tree from wasting levels: a balanced tree with n nodes has at most about 1.44 × log₂ n levels, so its height is still O(log n). Building one from sorted values is easy, and gives the fewest levels possible: make the middle value the root, so half the values go left and half go right, then do the same for each half. Real programs can't choose the order values arrive in, so self-balancing trees do the repair as they go. After each insert or delete they walk back up, and wherever two heights differ by 2, a rotation or two evens them out. Each repair is O(1) per level, so they keep searches at O(log n) whatever the order.
What it costs, by counting. Inserting n values that arrive sorted costs 0 + 1 + 2 + … + (n − 1) = n(n − 1)/2 comparisons, and the result searches in O(n):
- 15 values: chain height 15; built middle first, height 4
- 1,000 values: chain height 1,000 (499,500 comparisons to build); built middle first, height 10
- 1,000,000 values: chain height 1,000,000; built middle first, height 20
In Python there is no built-in BST. For "is it there?" use a set or dict (O(1) on average). For values kept in order, use a sorted list with bisect (searching is O(log n); inserting moves items, O(n), but is very fast in practice). For the smallest or biggest repeatedly, use heapq (Chapter 49). Balanced BSTs matter when you need all of these at once; libraries such as sortedcontainers give the same operations, built from sorted lists rather than a tree.
class Node:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
def build_balanced(values):
if not values:
return None
mid = len(values) // 2 # the middle value is the root...
return Node(values[mid],
build_balanced(values[:mid]), # ...the smaller half on its left
build_balanced(values[mid + 1:])) # ...the bigger half on its right
def is_balanced(root):
def h(node): # the height, or -1 as soon as a part is unbalanced
if node is None:
return 0
left, right = h(node.left), h(node.right)
if left == -1 or right == -1 or abs(left - right) > 1:
return -1
return 1 + max(left, right)
return h(root) != -1
def height(node):
return 0 if node is None else 1 + max(height(node.left), height(node.right))
def insert(root, x): # Lesson 48.2's insert as a loop (every value here is new)
new = Node(x)
if root is None:
return new
node = root
while True:
if x < node.val:
if node.left is None:
node.left = new
return root
node = node.left
else:
if node.right is None:
node.right = new
return root
node = node.right
chain = None
for x in range(1, 16):
chain = insert(chain, x) # sorted order: every value goes right
bushy = build_balanced(list(range(1, 16)))
print(height(chain), height(bushy))
print(is_balanced(chain), is_balanced(bushy))
print(bushy.val, bushy.left.val, bushy.right.val)Mistakes and edge cases.
- feeding a BST sorted data: files, registers and database results often come sorted; inserting them in that order builds a chain
- deep recursion on a chain: a recursive insert or search on a 5,000-node chain passes Python's limit of about 1,000 frames and raises
RecursionError; the loop version above doesn't - checking balance only at the root: a tree can have equal heights on both sides of the root and still be a chain lower down; the rule applies at every node
- thinking a BST is always O(log n): that holds only for a balanced one; the worst case of a plain BST is O(n)
values[mid]for an empty list: checkif not valuesfirst; the empty half is an empty tree
Quiz
What does this print?
class Node: def __init__(self, val, left=None, right=None): self.val = val self.left = left self.right = right def build_balanced(values): if not values: return None mid = len(values) // 2 # the middle value is the root... return Node(values[mid], build_balanced(values[:mid]), # ...the smaller half on its left build_balanced(values[mid + 1:])) # ...the bigger half on its right root = build_balanced([10, 20, 30, 40, 50, 60, 70]) print(root.val, root.left.val, root.right.val, root.left.left.val)The numbers 1 to 1,000 are inserted into an empty BST in increasing order. What is its height?
- 1,000
- 10
- 500
build_balanced is given the sorted numbers 1 to 100. How many levels does the tree have?
- 7
- 10
- 50
What does a rotation in a self-balancing tree keep the same?
- The inorder order of the values, so the BST rule still holds
- The height of every subtree
- Which node is the root
This says Node(1, Node(2, Node(3, Node(4))), Node(5, Node(6), Node(7))) is balanced, but at node 2 the heights are 2 and 0. Which line is wrong?
def height(node): return 0 if node is None else 1 + max(height(node.left), height(node.right)) def is_balanced(root): if root is None: return True return abs(height(root.left) - height(root.right)) <= 1
Coding tasks
Write
build_balanced(values):valuesis a sorted list of different numbers. Build a balanced BST holding them: the root is the middle value,values[len(values) // 2], the smaller values form the left subtree and the bigger ones the right, each built the same way. Return the root (Nonefor an empty list).Write
is_balanced(root):Trueif at every node the heights of the left and right subtrees differ by at most 1 (an empty tree is balanced).