Professional Documents
Culture Documents
Rotations
Muralidhara V N
IIIT Bangalore
AVL Tree
Z be a node where the AVL property is
violated.
Z Z Z Z
Y Y Y Y
X X X X
0=00 1=01 2=10 3=11
Replace the Subtree
Z be a node where the AVL property is
violated.
Z X/Y
Zig-Zig (0)
Z Y
Y
T4 Z
X
X
T3
T1 T2 T1 T2 T3 T4
Y
T1 Z X
X
T2
T1 T2 T3 T4
T3 T4
Y
T4 Z
Y
X
T1
T1 T2 T3 T4
T2 T3
Y
T1 Z Y
X
T4
T1 T2 T3 T4
T2 T3
In order Traversal of the both is T1 Z T2 X T3 Y T4
T2=X->left; T3=X->right; Y->left=T3; Z->right=T2;
X->p=Z->p; Z->p=X; Y->p=X; T2->p=Z;T3->p=Y;
X->left=Z;X->right=Y;
Deletion in AVL Tree
Goto the parent of the deleted node
1. check if the AVL property is violated.
2. update the height
T1 T2 T1 T2 T3 T4
X h-2
T1
h-2/h-3 T1 T2 T3 T4
T2 T3
h-2/h-3 h-3/h-4 h-3
h-3/h-4
Insert in AVL Tree
Goto the parent of the inserted node
1. update the height
2. check if the AVL property is violated.
Stop: If height does not change.
T1 T2 T1 T2 T3 T4
h-3
h-1
Y
T4 Z
h-2 Y h-2
X h-2
T1
h-3
T1 T2 T3 T4
T2 T3
h-3 h-3/h-4 h-3
h-3/h-4
Summery
Delete: You may have to do O(log n)
Rotations
• Search
• Insert
• Delete
52 11
4
6 26 73
15
2 3
19 32 64 93 2
1 1
29 39 85
1
1 1
Structure of the BBST
struct bst
{
long long int key;
long long int count;
int height;
struct bst *left, *right, *parent;
};
Count of a node
long long int Count (struct BST *node){
if (node){
if (node->left && node->right)
return 1 + node->left->count + node->right->count;
52 11
4
6 26 73
15
2 3
19 32 64 93 2
1 1
29 39 85
1
1 1
Find Rank (rank)
struct BST * FindRank (struct BST *node, long long int rank){
long long int r;
if (node && rank > 0 && rank < node->count + 1) {
while (node) {
if (node->right) r = node->right->count + 1;
else r = 1;
if (r == rank) return node;
else if (rank > r) {
node = node->left;
rank = rank - r;
}
else node = node->right;
} }
return NULL;
}
Rangecount(l,r)
long long int
Rangecount (struct BST *node, long long int l, long long int r)
{
long long int count;
count = Rank (node, l) - Rank (node, r);