algoritmauzmanı
Sign in
TREN
7.3AVL Tree
Lesson 7.3.6

Deleting from an AVL tree

Deletion also has two parts, like insertion. The first part is the same as deleting from a binary search tree: a leaf or a node with one child is removed directly, and a node with two children uses the inorder successor. The second part is calling rebalance on the way back. But deletion differs from insertion in one important way: one rotation may not be enough.

What you will learn
  • The one line that AVL deletion adds to BST deletion
  • That in deletion the child's balance factor can be 0, and that one rotation solves it
  • That one deletion may need several rotations, up to the root
8 minTime O(log n)Memory O(log n)C · Java · Python

1Idea

When the deleted node leaves the tree, the subtrees on the path from the root to that point may get one level shorter. Every node on the path is updated with rebalance. If the shorter side has dropped two levels below the other side, a rotation is done at that node. The cases are the four from insertion, but this time you look at the child opposite the side that got shorter.

Deletion brings a new case: the opposite child's balance factor can be 0. For example, the right side got shorter, the node's balance factor became 2, and the two subtrees of the left child have the same height. Then a single right rotation is enough; that is why the < 0 condition in rebalance leaves 0 to the LL side.

Why more than one rotation?

In insertion a rotation brings the subtree back to the height it had before the insertion, and nothing above notices. In deletion a rotation may not bring the subtree back to its height before the deletion: after the rotation the subtree can still be one level shorter. Then the balance of the node above may break too. This chain can go up to the root; in the worst case one rotation is done at every node on the path, that is O(log n) rotations.

102040306070509010012011080
Before the deletion. Every balance factor is 1 or 0: one of the sparsest possible AVL trees. 120 will be deleted.
102040306070509011010080
After 120 is deleted, 110 has balance factor 2: a right rotation at 110 (LL). But the subtree height went down from 2 to 1, and now 80 has balance factor 2.
102040306070901101008050
A right rotation at 80 too (LL). A single deletion needed rotations on two separate levels; the root is now 50.

If an exam asks about a deletion, keep rewriting the balance factors upwards after every rotation. The rule "one rotation is enough" from insertion does not hold for deletion.

2Step by step

The drawing deletes 20 from the AVL tree holding 30, 20, 40 and 50. The deletion makes the left side of 30 shorter.

30204050root
Call stack
  1. Start. 30 has balance factor -1 and 40 has -1. We will delete 20.
  2. 20 is smaller than 30: go left, and 20 is found.
  3. 20 is a leaf: both children are empty. child is NULL, the node is freed and NULL is returned.
  4. Back at 30: its left link is now NULL. rebalance(30): the left has height -1 and the right 1; the balance factor is -2. The right child 40 has -1: the RR case.
  5. A left rotation at 30: 40 moves up and 30 goes down to its left.
  6. Result: 40 at the root, height 1. Before the deletion the height was 2; the subtree got shorter, so if there were a node above, rebalance might have work to do there too.

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* deleteNode(struct AVLNode* root, int value) {    if (root == NULL) return NULL;               // value not in the tree    if (value < root->data) {        root->left = deleteNode(root->left, value);    } else if (value > root->data) {        root->right = deleteNode(root->right, value);    } else if (root->left == NULL || root->right == NULL) {        struct AVLNode* child = root->left ? root->left : root->right;        free(root);                              // a leaf or a node with one child        return child;                            // the child's subtree is already balanced    } else {                                     // two children: inorder successor        struct AVLNode* succ = root->right;        while (succ->left != NULL)            succ = succ->left;        root->data = succ->data;        root->right = deleteNode(root->right, root->data);    }    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 deleteNode(AVLNode root, int value) {    if (root == null) return null;               // value not in the tree    if (value < root.data) {        root.left = deleteNode(root.left, value);    } else if (value > root.data) {        root.right = deleteNode(root.right, value);    } else if (root.left == null || root.right == null) {        return root.left != null ? root.left : root.right;  // a leaf or one child    } else {                                     // two children: inorder successor        AVLNode succ = root.right;        while (succ.left != null)            succ = succ.left;        root.data = succ.data;        root.right = deleteNode(root.right, root.data);    }    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 delete_node(root, value):    if root is None:        return None  # value not in the tree    if value < root.data:        root.left = delete_node(root.left, value)    elif value > root.data:        root.right = delete_node(root.right, value)    elif root.left is None or root.right is None:        return root.left if root.left is not None else root.right  # a leaf or one child    else:  # two children: inorder successor        succ = root.right        while succ.left is not None:            succ = succ.left        root.data = succ.data        root.right = delete_node(root.right, root.data)    return rebalance(root)  # on the way back: update, rotate if needed

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

3Complexity

Time
O(log n)

Finding the node and its successor takes one path, and on the way back each node does O(1) work. The chained rotations are on the same path: O(log n).

Memory
O(log n)

Recursion stays open along the path: O(log n).

A deletion may do O(log n) rotations, but each rotation is O(1), so the total time is still O(log n).

4Common mistake

A common mistake is thinking that because the returned child is already balanced, the parent needs no rebalancing either:

if (value < root->data) {    root->left = deleteNode(root->left, value);    return root;         // rebalance not called: root may stay broken}

The returned child's own subtree is balanced, but its parent has one side that got shorter. rebalance must be called at every node on the way back. Another mistake on paper is stopping after the first rotation; with deletion you must check all the way to the root.

5Try it

On how many levels can a deletion from an AVL tree need rotations at most?

Show the answer

The answer is C. In deletion a rotation can leave the subtree shorter; then the balance of the node above breaks too. This chain can go up to the root.

After a deletion a node has balance factor 2 and its left child has 0. What is done?

Show the answer

The answer is A. The two subtrees of the left child have the same height. A single right rotation restores the balance; a double rotation is needed only if the left child leans right (-1).

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.