-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelf Balancing Tree.java
More file actions
72 lines (67 loc) · 1.96 KB
/
Self Balancing Tree.java
File metadata and controls
72 lines (67 loc) · 1.96 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
static Node insert(Node root,int val) {
if(root == null) {
root = new Node();
root.val = val;
root.ht = setHeight(root);
return root;
}
if(val <= root.val) {
root.left = insert(root.left, val);
}
else if (val > root.val) {
root.right = insert(root.right, val);
}
int balance = height(root.left) - height(root.right);
if(balance > 1) {
if(height(root.left.left) >= height(root.left.right)) {
root = rightRotation(root);
}
else {
root.left = leftRotation(root.left);
root = rightRotation(root);
}
}
else if(balance < -1) {
if(height(root.right.right) >= height(root.right.left)) {
root = leftRotation(root);
}
else {
root.right = rightRotation(root.right);
root = leftRotation(root);
}
}
else {
root.ht = setHeight(root);
}
return root;
}
private static Node rightRotation(Node root) {
Node newRoot = root.left;
root.left = newRoot.right;
newRoot.right = root;
root.ht = setHeight(root);
newRoot.ht = setHeight(newRoot);
return newRoot;
}
private static Node leftRotation(Node root) {
Node newRoot = root.right;
root.right = newRoot.left;
newRoot.left = root;
root.ht = setHeight(root);
newRoot.ht = setHeight(newRoot);
return newRoot;
}
private static int height(Node root) {
if(root == null)
return -1;
else
return root.ht;
}
private static int setHeight(Node root) {
if(root == null) {
return -1;
}
else {
return 1 + Math.max(height(root.left), height(root.right));
}
}