AVL Trees in Java
AVL Trees in Java
AVL Trees in Java
[email protected]
AVL Tree is a self-balancing BST.
Balance Factor in AVL tree = height(left Subtree) - height(right Subtree) and
always equal to {-1, 0, 1}
Node(int data) {
this.data = data;
height = 1;
}
}
[email protected]
// Right rotate subtree rooted with y
public static Node rightRotate(Node y) {
Node x = y.left;
Node T2 = x.right;
// update heights
y.height = Math.max(height(y.left), height(y.right)) + 1;
x.height = Math.max(height(x.left), height(x.right)) + 1;
// x is new root
return x;
}
// update heights
x.height = Math.max(height(x.left), height(x.right)) + 1;
y.height = Math.max(height(y.left), height(y.right)) + 1;
// y is new root
return y;
}
/* AVL Tree
30
/ \
20 40
/ \ \
10 25 50
*/
preorder(root);
}
}
AVL Tree Deletion
BST delete is a recursive function in which, after deletion, we get pointers to all ancestors one by one in
a bottom up manner. So we don’t need a parent pointer to travel up. The recursive code itself travels up
[email protected]
and visits all the ancestors of the deleted node.
[email protected]
temp = root.right;
else
temp = root.left;
// No child case
if (temp == null)
{
temp = root;
root = null;
}
else // One child case
root = temp; // Copy the contents of
// the non-empty child
}
else {
// node with two children: Get the inorder
// successor (smallest in the right subtree)
Node temp = getMinNode(root.right);
// Copy the inorder successor's data to this node
root.data = temp.data;
// Delete the inorder successor
root.right = deleteNode(root.right, temp.data);
}
}
// If the tree had only one node then return
if (root == null)
return root;
// update height of curr node
root.height = Math.max(height(root.left), height(root.right)) + 1;
// get balance factor of this node (to check for unbalanced)
int bf = getBalance(root);
// If this node becomes unbalanced, then there are 4 cases
// Left Left Case
if (bf > 1 && getBalance(root.left) >= 0)
return rightRotate(root);
// Left Right Case
if (bf > 1 && getBalance(root.left) < 0)
{
root.left = leftRotate(root.left);
return rightRotate(root);
}
[email protected]
// Right Right Case
if (bf < -1 && getBalance(root.right) <= 0)
return leftRotate(root);
// Right Left Case
if (bf < -1 && getBalance(root.right) > 0)
{
root.right = rightRotate(root.right);
return leftRotate(root);
}
return root;
}