-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVL Tree Insertion
77 lines (63 loc) Β· 1.93 KB
/
AVL Tree Insertion
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
class Solution{
public:
int height(Node* N){
if(N==NULL){
return 0;
}
return N->height;
}
int getBalance(Node* N){
if(N==NULL){
return 0;
}
return height(N->left)-height(N->right);
}
Node* leftRotation(Node* x){
Node* y = x->right;
Node* T2 = y->left;
y->left = x;
x->right = T2;
x->height = 1+max(height(x->left),height(x->right));
y->height = 1+max(height(y->left),height(y->right));
return y;
}
Node* rightRotation(Node* x){
Node* y = x->left;
Node* T2 = y->right;
y->right = x;
x->left = T2;
x->height = 1+max(height(x->left),height(x->right));
y->height = 1+max(height(y->left),height(y->right));
return y;
}
/*You are required to complete this method */
Node* insertToAVL(Node* node, int data)
{
if(node==NULL){
return new Node(data);
}else if(data > node->data){
node->right = insertToAVL(node->right,data);
}else if(data < node->data){
node->left = insertToAVL(node->left,data);
}else{
return node;
}
node->height = 1+max(height(node->left),height(node->right));
int balance = getBalance(node);
if(balance>1 && data < node->left->data){
return rightRotation(node);
}
if(balance<-1 && data>node->right->data){
return leftRotation(node);
}
if(balance>1 && data>node->left->data){
node->left = leftRotation(node->left);
return rightRotation(node);
}
if(balance<-1 && data<node->right->data){
node->right = rightRotation(node->right);
return leftRotation(node);
}
return node;
}
};