-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAVLTrees.java
More file actions
executable file
·60 lines (58 loc) · 1.44 KB
/
Copy pathAVLTrees.java
File metadata and controls
executable file
·60 lines (58 loc) · 1.44 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
/* Class node is defined as :
class Node
int val; //Value
int ht; //Height
Node left; //Left child
Node right; //Right child
*/
static Node insert(Node root,int val)
{
if (val < root.val)
{
if (root.left != null)
{
insert(root.left, val);
int difference = root.left.ht - root.right.ht;
int realDifference = Math.abs(difference);
if(realDifference > 1)
{
if (root.left.ht > root.right.ht)
{
if(root.left.left.ht > root.left.right.ht)
{
Node tempNode = new Node();
tempNode = root;
tempNode.left = root.left.right;
root.left.right = tempNode;
root = tempNode;
}
}
}
}
else
{
root.left = Node();
root.left = val;
if(root.right == null)
{
root.ht = root.ht + 1;
}
}
}
else if (val > root.val)
{
if (root.right != null)
{
insert(root.right, val);
}
else
{
root.right = Node();
root.right = val;
if(root.left == null)
{
root.ht = root.ht + 1;
}
}
}
}