algoritmauzmanı
Sign in
TREN
7.3AVL Tree
Lesson 7.3.1

AVL trees: height and balance factor

In the unbalanced trees lesson you saw sorted insertion turn a into a chain. The was the first way to prevent this: every node keeps its own , 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.

What you will learn
  • 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
6 minTime O(n)Memory O(h)C · Java · Python

1Idea

An AVL tree is a : 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 is 0 and an empty subtree is -1. A node's height is one more than the height of its taller child.

The 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 factorMeaningState
0Both subtrees have the same heightBalanced
1 or -1One side is one level tallerBalanced
2The left side is two levels tallerBroken: needs a right rotation
-2The right side is two levels tallerBroken: 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 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 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.

402050105root
Call stack
  1. Start. The tree is a BST, but we do not know yet whether it is AVL.
  2. isAVL checks the subtrees first: from 40 it goes down the left side to 20, 10 and 5.
  3. Both children of 5 are empty, and an empty tree is balanced. 5 has height 0 and balance factor 0 - 0 = 0.
  4. 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.
  5. 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.
  6. At 40 the left subtree returned false. The || operator never calls the right side: the function returns false without checking 50.
  7. 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 condition

The snippets focus on the operation in this lesson. The C examples need stdlib.h.

3Complexity

Time
O(n)

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

Memory
O(h)

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 30

Another 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?

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?

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.