public static class Node {
int data;
Node left;
Node right;
int height;
};
public int Height(Node p) {
if (p == null) {
return -1;
} else {
return p.height;
}
}
public Node rightRotate(Node k2)
{
Node k1;
k1 = k2.left;
k2.left = k1.right;
k1.right = k2;
k2.height = Math.max(Height(k2.left), Height(k2.right)) + 1;
k1.height = Math.max(Height(k1.left), k2.height) + 1;
return k1;
}
public Node DoubleRightRotate(Node k3) {
k3.left = rightRotate(k3.left);
return rightRotate(k3);
}
public Node Insert(int data, Node root) {
if (root == null) {
root = new Node();
root.data = data;
root.height = 0;
root.left = root.right = null;
} else if (data < root.data) {
root.left = Insert(data, root.left);
if (Height(root.left) - Height(root.right) == 2) {
if (data < root.left.data) {
root = rightRotate(root);
} else {
root.left = rightRotate(root.left);
root = rightRotate(root);
}
}
} else if (data < root.data) {
root.right = Insert(data, root.right);
if (Height(root.right) - Height(root.left) == 2){
if (data > root.right.data) {
root = leftRotate(root);
} else {
root.left = leftRotate(root.left);
root = leftRotate(root);
}
}
}
root.height = Math.max(Height(root.left), Height(root.right)) + 1;
return root;
}