-
Notifications
You must be signed in to change notification settings - Fork 47
/
Copy pathavlTree
86 lines (70 loc) · 1.66 KB
/
avlTree
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
#include<bits/stdc++.h>
using namespace std;
struct TreeNode
{
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
};
int height(TreeNode* root)
{
if(!root) return 0;
return max(height(root->left), height(root->right)) + 1;
}
int getbalance(TreeNode* root)
{
if(!root) return 0;
return height(root->left) - height(root->right);
}
TreeNode* leftRotation(TreeNode *root)
{
TreeNode *x, *y;
x = root->right;
y = x->left;
x->left = root;
root->right = y;
return x;
}
TreeNode* rightRotation(TreeNode *root)
{
TreeNode *x, *y;
x = root->left;
y = x->right;
x->right = root;
root->left = y;
return x;
}
TreeNode* insert(TreeNode* root, int value)
{
if(!root) return new TreeNode(value);
if(value > root->val) root->right = insert(root->right, value);
else root->left = insert(root->left, value);
int balance = getbalance(root);
if(balance > 1 && value < root->left->val)
{
return rightRotation(root);
}
if(balance > 1 && value > root->left->val)
{
root->left = leftRotation(root->left);
return rightRotation(root);
}
if(balance < -1 && value < root->right->val)
{
root->right = rightRotation(root->right);
return leftRotation(root);
}
if(balance < -1 && value > root->right->val) return leftRotation(root);
return root;
}
TreeNode* sortedArrayToBST(vector<int>& nums)
{
int n = nums.size();
TreeNode *root = NULL;
for(int i = 0; i < n; ++i)
{
root = insert(root, nums[i]);
}
return root;
}