AVL Deletion
Learn the deletion operation in AVL trees including all four deletion cases.
Deletion in AVL Trees
Deletion is almost similar to the insertion operation in AVLs with just one exception. The deletion operation adds an extra step after rotation and balances the first unbalanced node in the insertion method. After fixing the first unbalanced node through rotations, start moving up and fix the next unbalanced node. Keep fixing the unbalanced nodes until you reach the root.
Algorithm for deletion
Here is a high-level description of the algorithm for deletion.
1. Delete the given node
Delete the given node in the same way as BST deletion. At this point, the tree will become unbalanced. To rebalance the tree, you would need to perform some kind of rotation (left or right). At first, you will need to define the structure of the AVL tree and some nodes relative to the currentNode, which is inserted using step one.
2. Traverse upwards
Start traversing from the given node upwards until you find the first unbalanced node. Look at some of the terms, which you will be using while rebalancing the tree:
- Node U — An unbalanced node
- Node C — Child node of node U
- Node G — Grandchild node of node U
3. Rebalance the tree
To rebalance the tree, you will perform rotations on the subtree where U is the root node. There are two types of rotations (left and right). You came across four different scenarios based on the arrangements of nodes U, C, and G:
-
Left-Left: Node C is the left child of node U, and node G is the left child of node C.
-
Left-Right: Node C is the left child of node U, and node G is the right child of node C.
-
Right-Right: Node C is the right child of node U, and node G is the right child of node C.
-
Right-Left: Node C is the right child of node U, and node G is the left child of node C.
After performing successful rotation for the first unbalanced node U, traverse up and find the next unbalanced node, and perform the same series of operations to balance. Keep on balancing the unbalanced nodes from first node U to the ancestors of node U until you reach the root. After that point, you will have a fully balanced AVL tree that follows its property.
Case 1: Left-Left
Level up your interview prep. Join Educative to access 70+ hands-on prep courses.