Kodewick
Start learning →
Balanced trees: AVL39 / 52

Balanced trees: AVL

Lesson 39 of 52 · Part 7 · Searching · about 20 minutes

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.

8
4
2
6
10

The number under each node is its balance factor (left height − right height). Walking back after inserting 1, 2 and 4 become +1 and 8 becomes +2: out of balance

Working it out with chapter 4's plain BST insert, every node's balance factor listed in preorder:

main.py
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])
Output
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.

Choose one

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?

Exercise 1

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).

It should print
True False False True
3
exercise1.py
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))
Output
Press Run or Ctrl+Enter

The four rotations

Call the out-of-balance node t, and look at which side of which side of t the new node went:

CaseThe new node is int's balance factorRotation
LLthe left child's left subtree+2 (left child +1)rotate t right once
RRthe right child's right subtree−2 (right child −1)rotate t left once
LRthe left child's right subtree+2 (left child −1)rotate the left child left, then t right
RLthe 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.

8
4
2
1
6
10

LL: rotate 8 right. 4 comes up, 8 goes down as 4's right child; 4's old right child 6 moves to 8's left

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:

30
10

LR: insert 30, 10, 20. First rotate 10 left to make it LL, then rotate 30 right, and 20 is the root
Choose one

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?

Choose one

When node t is rotated right, where does the old right subtree of its left child l go?

Put in orderDrag, or use the arrows

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.

  1. fix(t)
  2. l.right = t
  3. l = t.left
  4. return l
  5. fix(l)
  6. t.left = l.right
Should print
[4, 2, 1, 8, 6, 10] 3
Exercise 2

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.

It should print
[2, 1, 3] 2
[2, 1, 3] 2
[30, 20, 10, 25, 40, 50] 3
exercise2.py
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)
Output
Press Run or Ctrl+Enter

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".

main.py
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)
Output
[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.

Guess the outputA wrong guess is fine

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)
Fill inTap one to fill a blank; tap a blank to take it back

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))

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:

1

1 2 3 4 5 inserted in order into an AVL tree: inserting 3 and inserting 5 each rotate left once, and it ends 3 high; a plain BST is a line, 5 high

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:

main.py
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))
Output
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 BSTAVL
Heightabout log n for random data, n when sortedalways ≤ 1.44 log₂ n
SearchO(h), worst O(n)O(log n)
InsertO(h), worst O(n)O(log n), rotates at one place at most
Extra per nodenothingthe 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.

Choose one

What makes a red-black tree better than an AVL tree?

Choose one

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: dict and set are 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: SortedList and SortedDict from 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:

main.py
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
Output
[20, 35, 50, 65]
35 50 None None
[35, 50]
You needIn Python useCost
Is it there, look up by keyset, dictO(1) on average, no order
Order and ranges, few insertssorted list + bisectsearch O(log n), insert O(n)
Only the smallest, again and againheapqtake and put are O(log n)
Order, many inserts and deletes, lots of datasortedcontainers (third-party) or a database indexabout O(log n)
Choose one

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?

Summary

Take-away

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