7.3AVL Tree
Inserting into an AVL tree
Inserting into an AVL tree has two parts. The first part is the same as inserting into a binary search tree: you go down from the root and put the value into an empty place as a leaf. The second part is the new one: as the recursion returns, every node on the path is updated with rebalance and rotated if its balance broke.
- Why an insertion only affects the path from the root to the new leaf
- How a rotation is done at the first node on the way back whose balance broke
- How to place a sequence of values into an AVL tree step by step, as in exams
1Idea
When a new leaf is added, only the nodes on the path from the root to that leaf can change height; the other subtrees are not touched. So there is no need to walk the whole tree to check the balance. The recursive insertion already walks this path once down and once up; on the way up rebalance is called at every node.
One rotation is done at the first node on the way back whose balance broke: single or double, depending on the case. After the rotation that subtree returns to the height it had before the insertion. So the nodes above see no change and rebalance does nothing at them. An insertion needs at most one (single or double) rotation.
The question exams ask most is inserting a sequence of values into an AVL tree in order. After every insertion, write the balance factors from the new leaf up to the root; at the first node where you see ±2, find the case and rotate. Example: 10, 20, 30, 40, 50, 25.
| Inserted | Balance broken at | Case | Tree (preorder) |
|---|---|---|---|
| 10 | None | 10 | |
| 20 | None | 10 20 | |
| 30 | 10 (bf = -2) | RR: left at 10 | 20 10 30 |
| 40 | None | 20 10 30 40 | |
| 50 | 30 (bf = -2) | RR: left at 30 | 20 10 40 30 50 |
| 25 | 20 (bf = -2) | RL: right at 40, left at 20 | 30 20 10 25 40 50 |
Look at 25 in the last row: 25 goes to the left of 40, which is on the right of 20. The right side of 20 grows (bf = -2), but the right child 40 is left-heavy (bf = 1). This is the RL case and it needs two rotations. The middle value 30 moves up to the root.
If you insert the numbers 1 to 1000 in order, an ordinary BST ends up with height 999. In an AVL tree the height is 9, the same as a perfectly balanced tree.
2Step by step
The drawing inserts 5 into the AVL tree holding 40, 20, 50 and 10. The stack on the right shows the open calls; under the nodes the updated height (h) and balance factor (df) are written.
- Start. The tree is AVL: 20 has balance factor 1 and 40 has 1. We will insert 5.
- 5 is smaller than 40: go left to 20.
- 5 is smaller than 20: go left to 10.
- 5 is smaller than 10 and the left of 10 is empty.
insert(NULL, 5)creates a new leaf with height 0. - Back at 10: its left link points to 5.
rebalance(10): height 1, balance factor 1. No rotation. - Back at 20.
rebalance(20): the left child 10 has height 1 and the right is empty. The balance factor is 2 and the left child's is 1: the LL case. - A right rotation at 20: 10 moves up and 20 goes down to its right. The subtree's height is 1 again, just as before the insertion.
- Back at 40, and its left link points to the new subtree root 10.
rebalance(40): height 2, balance factor 1. No change. - Result: the tree is AVL again. Every node has balance factor -1, 0 or 1.
struct AVLNode { int data; int height; struct AVLNode* left; struct AVLNode* right;}; int height(struct AVLNode* n) { return n == NULL ? -1 : n->height; // an empty subtree is -1} void update(struct AVLNode* n) { int l = height(n->left); int r = height(n->right); n->height = 1 + (l > r ? l : r); // one more than the taller child} int balanceFactor(struct AVLNode* n) { return height(n->left) - height(n->right);} struct AVLNode* rotateRight(struct AVLNode* y) { // 7.3.2 struct AVLNode* x = y->left; y->left = x->right; x->right = y; update(y); update(x); return x;} struct AVLNode* rotateLeft(struct AVLNode* x) { // 7.3.3 struct AVLNode* y = x->right; x->right = y->left; y->left = x; update(x); update(y); return y;} struct AVLNode* rebalance(struct AVLNode* n) { update(n); int bf = balanceFactor(n); if (bf > 1) { // left-heavy if (balanceFactor(n->left) < 0) // LR: first rotate the left child left n->left = rotateLeft(n->left); return rotateRight(n); // LL, or the second step of LR } if (bf < -1) { // right-heavy if (balanceFactor(n->right) > 0) // RL: first rotate the right child right n->right = rotateRight(n->right); return rotateLeft(n); // RR, or the second step of RL } return n; // balanced: nothing changes} struct AVLNode* insert(struct AVLNode* root, int value) { if (root == NULL) { // a new leaf in the empty place struct AVLNode* node = malloc(sizeof(struct AVLNode)); node->data = value; node->height = 0; node->left = NULL; node->right = NULL; return node; } if (value < root->data) root->left = insert(root->left, value); // find its place on the left else if (value > root->data) root->right = insert(root->right, value); // find its place on the right else return root; // an existing value is not added return rebalance(root); // on the way back: update, rotate if needed}class AVLNode { int data; int height; AVLNode left, right; AVLNode(int data) { this.data = data; }} int height(AVLNode n) { return n == null ? -1 : n.height; // an empty subtree is -1} void update(AVLNode n) { int l = height(n.left); int r = height(n.right); n.height = 1 + Math.max(l, r); // one more than the taller child} int balanceFactor(AVLNode n) { return height(n.left) - height(n.right);} AVLNode rotateRight(AVLNode y) { // 7.3.2 AVLNode x = y.left; y.left = x.right; x.right = y; update(y); update(x); return x;} AVLNode rotateLeft(AVLNode x) { // 7.3.3 AVLNode y = x.right; x.right = y.left; y.left = x; update(x); update(y); return y;} AVLNode rebalance(AVLNode n) { update(n); int bf = balanceFactor(n); if (bf > 1) { // left-heavy if (balanceFactor(n.left) < 0) // LR: first rotate the left child left n.left = rotateLeft(n.left); return rotateRight(n); // LL, or the second step of LR } if (bf < -1) { // right-heavy if (balanceFactor(n.right) > 0) // RL: first rotate the right child right n.right = rotateRight(n.right); return rotateLeft(n); // RR, or the second step of RL } return n; // balanced: nothing changes} AVLNode insert(AVLNode root, int value) { if (root == null) return new AVLNode(value); // a new leaf in the empty place if (value < root.data) root.left = insert(root.left, value); // find its place on the left else if (value > root.data) root.right = insert(root.right, value); // find its place on the right else return root; // an existing value is not added return rebalance(root); // on the way back: update, rotate if needed}class AVLNode: def __init__(self, data): self.data = data self.height = 0 self.left = None self.right = None def height(n): return -1 if n is None else n.height # an empty subtree is -1 def update(n): l = height(n.left) r = height(n.right) n.height = 1 + max(l, r) # one more than the taller child def balance_factor(n): return height(n.left) - height(n.right) def rotate_right(y): # 7.3.2 x = y.left y.left = x.right x.right = y update(y) update(x) return x def rotate_left(x): # 7.3.3 y = x.right x.right = y.left y.left = x update(x) update(y) return y def rebalance(n): update(n) bf = balance_factor(n) if bf > 1: # left-heavy if balance_factor(n.left) < 0: # LR: first rotate the left child left n.left = rotate_left(n.left) return rotate_right(n) # LL, or the second step of LR if bf < -1: # right-heavy if balance_factor(n.right) > 0: # RL: first rotate the right child right n.right = rotate_right(n.right) return rotate_left(n) # RR, or the second step of RL return n # balanced: nothing changes def insert(root, value): if root is None: return AVLNode(value) # a new leaf in the empty place if value < root.data: root.left = insert(root.left, value) # find its place on the left elif value > root.data: root.right = insert(root.right, value) # find its place on the right else: return root # an existing value is not added return rebalance(root) # on the way back: update, rotate if neededThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
The height of the tree is O(log n). Insertion walks this path once down and once up and does O(1) work at each node: O(log n).
Recursion keeps one call open per node on the path: O(log n).
In an ordinary BST insertion was O(n) in the worst case. The AVL tree limits the height, so the worst case is O(log n) too.
4Common mistake
A common mistake is ignoring the return value of rebalance:
root->left = insert(root->left, value);rebalance(root); // the new root after a rotation is lostreturn root;If a rotation happens, the root of the subtree changes, and the new root reaches the parent only through the return value. If you return the old root, part of the tree is cut off. On paper a common mistake is looking for the broken node from the top: the node rotated is the one closest to the new leaf, the first broken one from the bottom.
5Try it
If 1, 2, 3, 4, 5, 6, 7 are inserted into an empty AVL tree in that order, which value is the root?
The answer is B. Each RR case calls for a left rotation and the middle values move up. In the end 4 is at the root, 2 and 6 are its children and 1, 3, 5, 7 are the leaves: a perfect tree.
Show the answer
The answer is B. Each RR case calls for a left rotation and the middle values move up. In the end 4 is at the root, 2 and 6 are its children and 1, 3, 5, 7 are the leaves: a perfect tree.
At most how many rotation steps does one insertion into an AVL tree need?
The answer is A. The rotation at the first broken node returns the subtree to the height it had before the insertion. The nodes above see no change.
Show the answer
The answer is A. The rotation at the first broken node returns the subtree to the height it had before the insertion. The nodes above see no change.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.