Balanced trees: AVL
An AVL tree is a binary search tree that, after each insert, checks how far apart the heights of each node's two sides are and rotates when they differ by 2, keeping the height O(log n): 127 sorted numbers give a height of 7, not 127.
In chapter 4 we inserted 1 to 127 in order into a binary search tree: 8001 comparisons and a height of 127, exactly like a linked list. And real data is very often sorted already: auto-increment order IDs, timestamps, user names in alphabetical order. The AVL tree (by Adelson-Velsky and Landis in 1962, the first balanced tree) works like this: after every insert, walk back up the way you came and check at each node how far apart the heights of its two sides are; when they are 2 apart, a "rotation" sets it right. The same 127 sorted numbers give an AVL tree of height 7 and 762 comparisons.
Height and balance factor
Two definitions:
- A node's height: how many levels the subtree rooted at it has. An empty tree is 0, a leaf is 1.
- Balance factor = height of the left subtree − height of the right subtree.
An AVL tree is a binary search tree where every node's balance factor is −1, 0 or 1. Inserting a number changes heights only on the path from the root to the new node, so you only need to check that path, on the way back.
Working it out with chapter 4's plain BST insert, every node's balance factor listed in preorder:
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 7def insert(node, x): # chapter 4's plain BST8 if node is None:9 return TreeNode(x)10 if x < node.val:11 node.left = insert(node.left, x)12 elif x > node.val:13 node.right = insert(node.right, x)14 return node15 16def height(node): # empty tree 0, leaf 117 return 1 + max(height(node.left), height(node.right)) if node else 018 19def factors(node): # (value, balance factor) in preorder20 if node is None:21 return []22 b = height(node.left) - height(node.right)23 return [(node.val, b)] + factors(node.left) + factors(node.right)24 25root = None26for x in [8, 4, 10, 2, 6]:27 root = insert(root, x)28print(height(root), factors(root))29root = insert(root, 1)30print(height(root), factors(root))31print("out of balance:", [v for v, b in factors(root) if abs(b) > 1])
3 [(8, 1), (4, 0), (2, 0), (6, 0), (10, 0)] 4 [(8, 2), (4, 1), (2, 1), (1, 0), (6, 0), (10, 0)] out of balance: [8]
This height walks the whole subtree every time: O(n). An AVL tree can't afford that: it stores each node's height in the node and recomputes it only when a child changes, O(1) each time.
Insert 5, 3, 8, 1 in that order into an empty AVL tree (no rotation needed). What is the balance factor of the root, 5?
Is it balanced?
✓Complete check(node): if every node of this tree (which does not store heights) has left and right heights at most 1 apart, return its height; otherwise return -1. Looking at the root alone isn't enough: t3's root has equal sides, but the 2 below it is unbalanced. Walk the tree only once, O(n).
True False False True 3
1class TreeNode:2 def __init__(self, val, left=None, right=None):3 self.val = val4 self.left = left5 self.right = right6 7def check(node):8 # an empty tree is 0 high; if either side is -1, or they differ by more than 1, return -19 return 010 11def is_balanced(root):12 return check(root) != -113 14t1 = TreeNode(3, TreeNode(9), TreeNode(20, TreeNode(15), TreeNode(7)))15t2 = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4))), TreeNode(5))16t3 = TreeNode(1, TreeNode(2, TreeNode(3, TreeNode(4))), TreeNode(5, TreeNode(6, TreeNode(7))))17print(is_balanced(t1), is_balanced(t2), is_balanced(t3), is_balanced(None))18print(check(t1))
The four rotations
Call the out-of-balance node t, and look at which side of which side of t the new node went:
| Case | The new node is in | t's balance factor | Rotation |
|---|---|---|---|
| LL | the left child's left subtree | +2 (left child +1) | rotate t right once |
| RR | the right child's right subtree | −2 (right child −1) | rotate t left once |
| LR | the left child's right subtree | +2 (left child −1) | rotate the left child left, then t right |
| RL | the right child's left subtree | −2 (right child +1) | rotate the right child right, then t left |
Rotate right: t's left child l comes up as this subtree's root, t goes down as l's right child, and l's old right subtree moves to t's left. It is bigger than l and smaller than t, so it fits right there, and the inorder (small to large) doesn't change. Rotating left is its mirror.
After the rotation this subtree is as high as before the insert, so nothing further up can be out of balance because of this insert. One insert rotates at one place at most (LR and RL count as one place, two turns).
LR needs more than one turn: the new node is on the left child's right, and a plain right rotation carries it over to the other side, still out of balance. Rotate the left child left first, which turns it into LL, then rotate right:
Insert 30, 10, 20 in that order into an empty AVL tree. Which kind of imbalance is it, and what is the root after the fix?
When node t is rotated right, where does the old right subtree of its left child l go?
Put the 6 lines of rot_right in order: the left child l moves up, t goes down as l's right child, l's old right subtree hangs on t's left; then recompute the heights.
fix(t)l.right = tl = t.leftreturn lfix(l)t.left = l.right
[4, 2, 1, 8, 6, 10] 3
t.left = l.right must come before l.right = t, or l's old right subtree is lost. t is now lower, so fix(t) first, because l's height needs t's new one. Finally return the new root, l.Write a left rotation
✓rot_right is already written. Following it, complete rot_left: the right child r comes up, t becomes r's left child, and r's old left subtree moves to t's right; recompute t's height first, then r's.
[2, 1, 3] 2 [2, 1, 3] 2 [30, 20, 10, 25, 40, 50] 3
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 self.height = 17 8def h(node):9 return node.height if node else 010 11def fix(node):12 node.height = 1 + max(h(node.left), h(node.right))13 14def rot_right(t):15 l = t.left16 t.left = l.right17 l.right = t18 fix(t)19 fix(l)20 return l21 22def rot_left(t):23 # the right child comes up24 return t25 26def insert(node, x):27 if node is None:28 return TreeNode(x)29 if x < node.val:30 node.left = insert(node.left, x)31 else:32 node.right = insert(node.right, x)33 fix(node)34 b = h(node.left) - h(node.right)35 if b > 1:36 if h(node.left.left) < h(node.left.right):37 node.left = rot_left(node.left)38 return rot_right(node)39 if b < -1:40 if h(node.right.right) < h(node.right.left):41 node.right = rot_right(node.right)42 return rot_left(node)43 return node44 45def pre(node):46 return [node.val] + pre(node.left) + pre(node.right) if node else []47 48for order in [[1, 2, 3], [1, 3, 2], [10, 20, 30, 40, 50, 25]]:49 root = None50 for x in order:51 root = insert(root, x)52 print(pre(root), root.height)
Writing an AVL insert
Each node stores one more field, height. A rotation changes the children of only two nodes, so only those two heights are recomputed, first t, which is now below, then the one above. The insert is chapter 4's recursion with one more line before it returns, rebalance: the way back from the recursion is exactly the path "from the new node up to the root".
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 self.height = 1 # a new node is a leaf, height 17 8def h(node):9 return node.height if node else 010 11def fix(node): # after a child changes, recompute my height12 node.height = 1 + max(h(node.left), h(node.right))13 14def balance(node): # balance factor: left height − right height15 return h(node.left) - h(node.right)16 17def rot_right(t): # the left child comes up18 l = t.left19 t.left = l.right20 l.right = t21 fix(t) # t is below now: compute it first22 fix(l)23 return l24 25def rot_left(t): # the right child comes up26 r = t.right27 t.right = r.left28 r.left = t29 fix(t)30 fix(r)31 return r32 33rotations = []34 35def rebalance(node):36 fix(node)37 b = balance(node)38 if b > 1: # left-heavy39 if balance(node.left) < 0: # LR: rotate the left child left first, making it LL40 node.left = rot_left(node.left)41 rotations.append("LR")42 else:43 rotations.append("LL")44 return rot_right(node)45 if b < -1: # right-heavy46 if balance(node.right) > 0: # RL: rotate the right child right first, making it RR47 node.right = rot_right(node.right)48 rotations.append("RL")49 else:50 rotations.append("RR")51 return rot_left(node)52 return node53 54def insert(node, x):55 if node is None:56 return TreeNode(x)57 if x < node.val:58 node.left = insert(node.left, x)59 elif x > node.val:60 node.right = insert(node.right, x)61 else:62 return node # already there63 return rebalance(node) # on the way back, check every level64 65def pre(node):66 return [node.val] + pre(node.left) + pre(node.right) if node else []67 68for order in [[3, 2, 1], [1, 2, 3], [3, 1, 2], [1, 3, 2], [8, 4, 10, 2, 6, 1]]:69 rotations.clear()70 root = None71 for x in order:72 root = insert(root, x)73 print(order, "preorder", pre(root), "height", root.height, rotations)
[3, 2, 1] preorder [2, 1, 3] height 2 ['LL'] [1, 2, 3] preorder [2, 1, 3] height 2 ['RR'] [3, 1, 2] preorder [2, 1, 3] height 2 ['LR'] [1, 3, 2] preorder [2, 1, 3] height 2 ['RL'] [8, 4, 10, 2, 6, 1] preorder [4, 2, 1, 8, 6, 10] height 3 ['LL']
Inserting 1, 2, 3 in the four orders, the rotations all end in the same tree: 2 at the root. [8, 4, 10, 2, 6, 1] is the LL picture in the "four rotations" stage.
Insert 1 to 7 in order into an AVL tree. It prints the preorder and the height:
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 self.height = 17 8def h(node):9 return node.height if node else 010 11def fix(node):12 node.height = 1 + max(h(node.left), h(node.right))13 14def rot_right(t):15 l = t.left16 t.left = l.right17 l.right = t18 fix(t)19 fix(l)20 return l21 22def rot_left(t):23 r = t.right24 t.right = r.left25 r.left = t26 fix(t)27 fix(r)28 return r29 30def insert(node, x):31 if node is None:32 return TreeNode(x)33 if x < node.val:34 node.left = insert(node.left, x)35 else:36 node.right = insert(node.right, x)37 fix(node)38 b = h(node.left) - h(node.right)39 if b > 1:40 if h(node.left.left) < h(node.left.right):41 node.left = rot_left(node.left)42 return rot_right(node)43 if b < -1:44 if h(node.right.right) < h(node.right.left):45 node.right = rot_right(node.right)46 return rot_left(node)47 return node48 49def pre(node):50 return [node.val] + pre(node.left) + pre(node.right) if node else []51 52root = None53for x in range(1, 8):54 root = insert(root, x)55print(pre(root), root.height)
Which rotation does the LL case (the new node to the left of the left child) call? Fill in the blank so the tree built from 7 down to 1 stays balanced.
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 self.height = 17 8def h(node):9 return node.height if node else 010 11def fix(node):12 node.height = 1 + max(h(node.left), h(node.right))13 14def rot_right(t):15 l = t.left16 t.left = l.right17 l.right = t18 fix(t)19 fix(l)20 return l21 22def rot_left(t):23 r = t.right24 t.right = r.left25 r.left = t26 fix(t)27 fix(r)28 return r29 30def insert(node, x):31 if node is None:32 return TreeNode(x)33 if x < node.val:34 node.left = insert(node.left, x)35 else:36 node.right = insert(node.right, x)37 fix(node)38 b = h(node.left) - h(node.right)39 if b > 1 and x < node.left.val:40 return (node)41 if b < -1 and x > node.right.val:42 return rot_left(node)43 if b > 1:44 node.left = rot_left(node.left)45 return rot_right(node)46 if b < -1:47 node.right = rot_right(node.right)48 return rot_left(node)49 return node50 51def pre(node):52 return [node.val] + pre(node.left) + pre(node.right) if node else []53 54root = None55for x in range(7, 0, -1):56 root = insert(root, x)57print(*pre(root))
rot_right. With rot_left, it reaches for a right child that isn't there and the program stops.Counting: sorted input
Draw 1 to 5 inserted in order into an AVL tree once more. Each time it goes out of balance it is RR, one left rotation:
Compare with chapter 4's example: the plain BST inserts with a loop (a line is 127 levels, too deep for recursion), the AVL tree with the recursive insert from the "write an AVL insert" stage (its depth is the tree's height, about ten levels). Count the comparisons of each:
1class TreeNode:2 def __init__(self, val):3 self.val = val4 self.left = None5 self.right = None6 self.height = 17 8def h(node):9 return node.height if node else 010 11def fix(node):12 node.height = 1 + max(h(node.left), h(node.right))13 14def rot_right(t):15 l = t.left16 t.left = l.right17 l.right = t18 fix(t)19 fix(l)20 return l21 22def rot_left(t):23 r = t.right24 t.right = r.left25 r.left = t26 fix(t)27 fix(r)28 return r29 30def rebalance(node):31 fix(node)32 b = h(node.left) - h(node.right)33 if b > 1:34 if h(node.left.left) < h(node.left.right):35 node.left = rot_left(node.left)36 return rot_right(node)37 if b < -1:38 if h(node.right.right) < h(node.right.left):39 node.right = rot_right(node.right)40 return rot_left(node)41 return node42 43cmps = 044 45def avl_insert(node, x):46 global cmps47 if node is None:48 return TreeNode(x)49 cmps += 150 if x < node.val:51 node.left = avl_insert(node.left, x)52 else:53 node.right = avl_insert(node.right, x)54 return rebalance(node)55 56def bst_insert(root, x): # chapter 4's plain BST, written with a loop57 global cmps58 if root is None:59 return TreeNode(x)60 node = root61 while True:62 cmps += 163 if x < node.val:64 if node.left is None:65 node.left = TreeNode(x)66 return root67 node = node.left68 else:69 if node.right is None:70 node.right = TreeNode(x)71 return root72 node = node.right73 74def height(node): # count level by level, no recursion75 d = 076 level = [node] if node else []77 while level:78 d += 179 level = [c for n in level for c in (n.left, n.right) if c]80 return d81 82for n, name, ins in [(127, "a plain BST", bst_insert), (127, "an AVL tree", avl_insert), (255, "an AVL tree", avl_insert)]:83 cmps = 084 root = None85 for x in range(1, n + 1):86 root = ins(root, x)87 print("1 to", n, "in order into " + name + ":", cmps, "comparisons, height", height(root))
1 to 127 in order into a plain BST: 8001 comparisons, height 127 1 to 127 in order into an AVL tree: 762 comparisons, height 7 1 to 255 in order into an AVL tree: 1785 comparisons, height 8
127 numbers: the plain BST is 127 high, the AVL tree 7 (127 = 2⁷ − 1, exactly a full tree). With 255 numbers the AVL tree is 8 high; the plain BST would be 255 levels and 32,385 comparisons. Even 1023 numbers make an AVL tree only 10 high. It can be proved that an AVL tree's height is at most about 1.44 log₂ n, so search and insert are O(log n) whatever order the data comes in.
| Plain BST | AVL | |
|---|---|---|
| Height | about log n for random data, n when sorted | always ≤ 1.44 log₂ n |
| Search | O(h), worst O(n) | O(log n) |
| Insert | O(h), worst O(n) | O(log n), rotates at one place at most |
| Extra per node | nothing | the height (one integer) |
In interviews: you are rarely asked to write a whole AVL tree, but often asked "why does a BST need balancing?", "what are the four rotation cases?", "AVL vs red-black tree?" (AVL is shorter and searches faster, but rotates more on inserts and deletes; a red-black tree only requires the longest path to be at most twice the shortest, so it rotates less; C++'s std::map and Java's TreeMap are red-black trees). The coding question that comes up is its neighbour, "is this tree balanced?", which is the exercise "is it balanced?" in the first stage.
What makes a red-black tree better than an AVL tree?
Insert 1 to 1023 in order into an AVL tree. How tall is it?
How you write it at work
Python's standard library has no balanced tree, and so no sorted set or dict like C++'s std::map or Java's TreeMap. The reasons are practical:
- Most of the time you only ask "is it there?" or look up by key:
dictandsetare hash tables, O(1) on average, faster than any tree. - For order and ranges: a sorted list plus
bisect. Search is O(log n); insert is O(n), but the move is one block memory copy in C, and up to tens of thousands it beats a tree written in Python (every node of such a tree is a Python object, and each step is an attribute lookup). - Really big, with many inserts and deletes:
SortedListandSortedDictfrom the third-party library sortedcontainers. It isn't a tree either: it splits the data into many small sorted lists, so an insert only moves a short piece. This course's code can't import it; just know it exists.
This is what "a sorted list used as a sorted set" looks like:
1from bisect import bisect_left, bisect_right2 3ids = []4 5def add(x): # only if absent: stays sorted, no repeats6 i = bisect_left(ids, x)7 if i == len(ids) or ids[i] != x:8 ids.insert(i, x)9 10def remove(x):11 i = bisect_left(ids, x)12 if i < len(ids) and ids[i] == x:13 del ids[i]14 15def floor(x): # the largest one not above x16 i = bisect_right(ids, x)17 return ids[i - 1] if i else None18 19def ceiling(x): # the smallest one not below x20 i = bisect_left(ids, x)21 return ids[i] if i < len(ids) else None22 23for x in [50, 20, 80, 20, 65, 35]:24 add(x)25remove(80)26print(ids)27print(floor(40), ceiling(40), floor(10), ceiling(99))28print(ids[bisect_left(ids, 30):bisect_right(ids, 60)]) # the ones from 30 to 60
[20, 35, 50, 65] 35 50 None None [35, 50]
| You need | In Python use | Cost |
|---|---|---|
| Is it there, look up by key | set, dict | O(1) on average, no order |
| Order and ranges, few inserts | sorted list + bisect | search O(log n), insert O(n) |
| Only the smallest, again and again | heapq | take and put are O(log n) |
| Order, many inserts and deletes, lots of data | sortedcontainers (third-party) or a database index | about O(log n) |
In Python you need an ordered collection: you often ask "the first one ≥ 60" or "how many between 60 and 80", but you rarely insert. What fits best?
bisect. A set has no order, so it can't answer "the first one ≥ 60"; heapq is only good at taking the smallest; a hand-written AVL tree makes every node a Python object, and up to tens of thousands of items it is actually slower than a list.Summary
AVL: walk back after inserting, rotate at a difference of 2
- Balance factor = left height − right height; AVL keeps every node within −1 to 1
- LL rotates right, RR rotates left; LR rotates the left child left then right, RL the other way
- Store heights in nodes; after a rotation fix the lower node, then the upper; rebalance on the way back
- Height ≤ 1.44 log₂ n: O(log n) even on sorted input
- Python has no sorted set / dict: dict, set, sorted list + bisect, or sortedcontainers
1def rot_right(t):2 l = t.left3 t.left, l.right = l.right, t4 fix(t); fix(l)5 return l