-
Notifications
You must be signed in to change notification settings - Fork 1
/
avl-tree-insertion.java
95 lines (75 loc) · 2.5 KB
/
avl-tree-insertion.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
85
86
87
88
89
90
91
92
93
94
95
class Solution
{
// Helper function to calculate height of a node
int height(Node N) {
if (N == null)
return 0;
return N.height;
}
// Helper function to perform left rotation
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
return y;
}
// Helper function to perform right rotation
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
return x;
}
// Helper function to get balance factor of a node
int getBalance(Node N) {
if (N == null)
return 0;
return height(N.left) - height(N.right);
}
// Helper function to balance the tree after an insertion
Node balance(Node root, int data) {
// Update height of current node
root.height = Math.max(height(root.left), height(root.right)) + 1;
// Get the balance factor
int balance = getBalance(root);
// Left Left Case
if (balance > 1 && data < root.left.data)
return rightRotate(root);
// Right Right Case
if (balance < -1 && data > root.right.data)
return leftRotate(root);
// Left Right Case
if (balance > 1 && data > root.left.data) {
root.left = leftRotate(root.left);
return rightRotate(root);
}
// Right Left Case
if (balance < -1 && data < root.right.data) {
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
}
// Insert a node into the AVL tree
public Node insertToAVL(Node root, int data) {
// Perform standard BST insertion
if (root == null)
return new Node(data);
if (data < root.data)
root.left = insertToAVL(root.left, data);
else if (data > root.data)
root.right = insertToAVL(root.right, data);
else // Duplicate data not allowed
return root;
// Update height of current node
root.height = 1 + Math.max(height(root.left), height(root.right));
// Balance the tree
return balance(root, data);
}
}