-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVL Tree (BST).cpp
More file actions
135 lines (116 loc) · 2.61 KB
/
Copy pathAVL Tree (BST).cpp
File metadata and controls
135 lines (116 loc) · 2.61 KB
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
// AVL TREE
#include <bits/stdc++.h>
#define ll long long
#define REP(i,a,b) for(int i = a; i < b; ++i)
#define REPI(i,a,b) for(int i = b - 1; i >= a; --i)
using namespace std;
struct Node{
int val;
struct Node *left, *right;
int height;
};
struct Node* createNewNode(int val)
{
struct Node *tmp = new struct Node();
tmp->val = val;
tmp->left = tmp->right = nullptr;
tmp->height = 1;
return tmp;
}
int getHeight(struct Node *root)
{
if(root == nullptr)
{
return 0;
}
return (root->height);
}
int getBalanceFactor(struct Node *root)
{
if(root == nullptr)
{
return 0;
}
return getHeight(root->left) - getHeight(root->right);
}
struct Node* leftRotation(struct Node *x)
{
struct Node *y = x->right;
struct Node *t = y->left;
y->left = x;
x->right = t;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
struct Node* rightRotation(struct Node *x)
{
struct Node *y = x->left;
struct Node *t = y->right;
y->right = x;
x->left = t;
x->height = max(getHeight(x->left), getHeight(x->right)) + 1;
y->height = max(getHeight(y->left), getHeight(y->right)) + 1;
return y;
}
struct Node* insert(struct Node *root, int key)
{
if(root == nullptr)
{
struct Node *t = createNewNode(key);
return t;
}
if(key < root->val)
{
root->left = insert(root->left, key);
}
else if(root->val < key)
{
root->right = insert(root->right, key);
}
root->height = max(getHeight(root->left), getHeight(root->right)) + 1;
int bf = getBalanceFactor(root);
if(bf > 1 )
{
if(key < root->left->val)
{
root = rightRotation(root);
}
else
{
root->left = leftRotation(root->left);
root = rightRotation(root);
}
}
if(bf < -1 )
{
if(key > root->right->val)
{
root = leftRotation(root);
}
else
{
root->right = rightRotation(root->right);
root = leftRotation(root);
}
}
return root;
}
void preorder(struct Node *root)
{
if(root == nullptr) return;
cout << root->val << endl;
preorder(root->left);
preorder(root->right);
}
int main()
{
struct Node * root = nullptr;
root = insert(root, 1);
root = insert(root, 2);
root = insert(root, 4);
root = insert(root, 5);
root = insert(root, 6);
root = insert(root, 3);
preorder(root);
}