AVL Tree Implementation in Java
AVL Tree Implementation in Java
// Create node
class Node {
Node(int d) {
item = d;
height = 1;
// Tree class
class AVLTree {
Node root;
int height(Node N) {
if (N == null)
return 0;
return N.height;
return (a > b) ? a : b;
Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
x.right = y;
y.left = T2;
return x;
Node leftRotate(Node x) {
Node y = x.right;
Node T2 = y.left;
y.left = x;
x.right = T2;
return y;
int getBalanceFactor(Node N) {
if (N == null)
return 0;
// Insert a node
else
return node;
if (balanceFactor > 1) {
return rightRotate(node);
node.left = leftRotate(node.left);
return rightRotate(node);
return leftRotate(node);
node.right = rightRotate(node.right);
return leftRotate(node);
}
return node;
current = current.left;
return current;
// Delete a node
if (root == null)
return root;
else {
if (temp == root.left)
temp = root.right;
else
temp = root.left;
if (temp == null) {
temp = root;
root = null;
} else
root = temp;
} else {
root.item = temp.item;
if (root == null)
return root;
// Update the balance factor of each node and balance the tree
if (balanceFactor > 1) {
if (getBalanceFactor(root.left) >= 0) {
return rightRotate(root);
} else {
root.left = leftRotate(root.left);
return rightRotate(root);
if (getBalanceFactor(root.right) <= 0) {
return leftRotate(root);
} else {
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
if (node != null) {
preOrder(node.left);
preOrder(node.right);
if (currPtr != null) {
System.out.print(indent);
if (last) {
System.out.print("R----");
} else {
System.out.print("L----");
System.out.println(currPtr.item);
}
// Driver code