7.3AVL Tree
AVL trees: height and balance factor
In the unbalanced trees lesson you saw sorted insertion turn a binary search tree into a chain. The AVL tree was the first way to prevent this: every node keeps its own height, and the heights of its two subtrees may differ by at most 1. This lesson covers the rule itself and the code that checks it; the next lessons do the fixing.
- How to compute a node's height from its children
- The balance factor and the AVL rule (-1, 0 or 1)
- How to check from the bottom up whether a tree is AVL
1Idea
An AVL tree is a binary search tree: smaller values on the left, larger on the right. The only difference is one more field in every node: height. Height counts edges as in the previous part; a leaf is 0 and an empty subtree is -1. A node's height is one more than the height of its taller child.
The balance factor is the height of the left subtree minus the height of the right subtree. If it is positive the node is left-heavy, if negative right-heavy. The AVL rule: the balance factor is -1, 0 or 1 at every node. The rule is checked at every node, not only at the root.
| Balance factor | Meaning | State |
|---|---|---|
| 0 | Both subtrees have the same height | Balanced |
| 1 or -1 | One side is one level taller | Balanced |
| 2 | The left side is two levels taller | Broken: needs a right rotation |
| -2 | The right side is two levels taller | Broken: needs a left rotation |
Counting the height from scratch every time would take O(n). So the height is stored in the node and refreshed with update only on the nodes along the changed path. update assumes the children's heights are ready, so it is always called from the bottom up.
This lesson's isAVL function is a postorder traversal: it checks both subtrees first, then writes the node's height and tests the rule. That way it can also check a tree whose height fields are not filled in yet. You solve the exam question "is this tree AVL?" on paper in the same order.
The AVL rule limits the height of the tree: an AVL tree with n nodes is at most about 1.44 · log₂ n tall. For a million nodes that is 29; search, insertion and deletion stay O(log n) even in the worst case.
2Step by step
The drawing checks the tree holding 40, 20, 50, 10 and 5. Under each node, once update has run, its height (h) and balance factor (bf, shown as df) are written.
- Start. The tree is a BST, but we do not know yet whether it is AVL.
isAVLchecks the subtrees first: from 40 it goes down the left side to 20, 10 and 5.- Both children of 5 are empty, and an empty tree is balanced. 5 has height 0 and balance factor 0 - 0 = 0.
- Back at 10. Its right is empty. The left child 5 has height 0, the right -1: height 1, balance factor 0 - (-1) = 1. The rule holds.
- Back at 20. The left child 10 has height 1, the right is empty (-1): height 2, balance factor 2. The rule is broken and the function returns false.
- At 40 the left subtree returned false. The
||operator never calls the right side: the function returns false without checking 50. - Result: the tree is not AVL, and the problem is at 20. Its left side is two levels taller; the next lesson fixes it with a right rotation.
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);} bool isAVL(struct AVLNode* n) { if (n == NULL) return true; // an empty tree is balanced if (!isAVL(n->left) || !isAVL(n->right)) return false; // a subtree is broken update(n); // children are ready: set the height int bf = balanceFactor(n); return bf >= -1 && bf <= 1; // the AVL condition}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);} boolean isAVL(AVLNode n) { if (n == null) return true; // an empty tree is balanced if (!isAVL(n.left) || !isAVL(n.right)) return false; // a subtree is broken update(n); // children are ready: set the height int bf = balanceFactor(n); return bf >= -1 && bf <= 1; // the AVL condition}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 is_avl(n): if n is None: return True # an empty tree is balanced if not is_avl(n.left) or not is_avl(n.right): return False # a subtree is broken update(n) # children are ready: set the height bf = balance_factor(n) return -1 <= bf <= 1 # the AVL conditionThe snippets focus on the operation in this lesson. The C examples need stdlib.h.
3Complexity
Every node is visited once and does constant work: O(n). Insertion and deletion update only the nodes on the changed path: O(log n).
Recursion keeps as many calls open as the height of the tree: O(h). In an AVL tree h is O(log n).
Because the height is stored in the node, height and balanceFactor take O(1). The speed of the AVL tree rests on this.
4Common mistake
A common mistake is looking only at the root's balance factor. The difference at the root can be 0 while a subtree is broken. Both sides of the root below have height 2, yet the tree is not AVL:
// 50// / \// 30 70// / \// 20 80// / \// 10 90// bf = 2 - 2 = 0 at the root, but bf = 2 at 30Another mistake is mixing up height and node count. A leaf is 0 and an empty subtree -1; if you take a single node's height as 1, the formulas shift by one. Some books define it that way; you saw the difference in the node count and height lesson.
5Try it
A node's left subtree has height 3 and its right subtree is empty. What is its balance factor?
The answer is B. An empty subtree has height -1. The balance factor is 3 - (-1) = 4. This node clearly breaks the AVL rule.
Show the answer
The answer is B. An empty subtree has height -1. The balance factor is 3 - (-1) = 4. This node clearly breaks the AVL rule.
Which is true for an AVL tree?
The answer is B. The AVL rule is checked at every node separately. In an AVL tree the leaves may sit on different levels; the rule only limits the height difference of the two subtrees.
Show the answer
The answer is B. The AVL rule is checked at every node separately. In an AVL tree the leaves may sit on different levels; the rule only limits the height difference of the two subtrees.
Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.