-
Notifications
You must be signed in to change notification settings - Fork 0
/
AVL.java
84 lines (82 loc) · 1.81 KB
/
AVL.java
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
class Node{
int val;
int ht;
Node left;
Node right;
}
class AVL {
Node root;
AVL(){
root=null;
}
Node insert(Node root,int val)
{
Node nptr=new Node();
nptr.val=val;
nptr.left=null;
nptr.right=null;
nptr.ht=0;
if(root==null){
root=nptr;
return root;
}
if(val<=root.val){
root.left=insert(root.left,val);
}
else{
root.right=insert(root.right,val);
}
int lh=height(root.left);
int rh=height(root.right);
if(Math.abs(lh-rh)>1){
if(lh>rh){
if(height(root.left.right)>height(root.left.left))
root.left=RightRotate(root.left);
root=LeftRotate(root);
}
else{
if(height(root.right.left)>height(root.right.right))
root.right=LeftRotate(root.right);
root=RightRotate(root);
}
}
root.ht=height(root);
return root;
}
int height(Node roote){
if(roote==null) return -1;
int left;
if(roote.left==null) left=-1;
else left=roote.left.ht;
int right;
if(roote.right==null) right=-1;
else right=roote.right.ht;
if(left>right) return left+1;
else return right+1;
}
Node LeftRotate(Node prev){
Node newr=prev.left;
Node child=newr.right;
prev.left=child;
newr.right=prev;
prev.ht=height(prev);
newr.ht=height(newr);
return newr;
}
Node RightRotate(Node prev){
Node newr=prev.right;
Node child=newr.left;
prev.right=child;
newr.left=prev;
prev.ht=height(prev);
newr.ht=height(newr);
return newr;
}
void inorder(Node roote) {
if(roote!=null) {
inorder(roote.left);
System.out.print(roote.val+" ");
inorder(roote.right);
}
}
}