What is an AVL Tree?
An AVL Tree is a self-balancing Binary Search Tree where the height difference
(balance factor) between a node’s left and right subtrees is at most 1.
It maintains this by performing rotations after insertions and deletions.
AVL Tree Insertion
function insert(node, key):
if node is null:
return new Node(key)
if key < node.key:
node.left = insert(node.left, key)
else if key > node.key:
node.right = insert(node.right, key)
else:
return node # no duplicates
updateHeight(node)
balance = getBalance(node)
# Left Left
if balance > 1 and key < node.left.key:
return rightRotate(node)
# Right Right
if balance < -1 and key > node.right.key:
return leftRotate(node)
# Left Right
if balance > 1 and key > node.left.key:
node.left = leftRotate(node.left)
return rightRotate(node)
# Right Left
if balance < -1 and key < node.right.key:
node.right = rightRotate(node.right)
return leftRotate(node)
return node
AVL Tree Deletion
function delete(node, key):
if node is null:
return null
# 1) Standard BST delete
if key < node.key:
node.left = delete(node.left, key)
else if key > node.key:
node.right = delete(node.right, key)
else:
# node with one child or no child
if node.left is null or node.right is null:
temp = node.left ? node.left : node.right
if temp is null:
node = null
else:
node = temp
else:
# two children: inorder successor from right subtree
succ = minValueNode(node.right)
node.key = succ.key
node.right = delete(node.right, succ.key)
if node is null:
return node
# 2) Update height
node.height = 1 + max(height(node.left), height(node.right))
# 3) Rebalance
balance = getBalance(node)
# Left Left
if balance > 1 and getBalance(node.left) >= 0:
return rightRotate(node)
# Left Right
if balance > 1 and getBalance(node.left) < 0:
node.left = leftRotate(node.left)
return rightRotate(node)
# Right Right
if balance < -1 and getBalance(node.right) <= 0:
return leftRotate(node)
# Right Left
if balance < -1 and getBalance(node.right) > 0:
node.right = rightRotate(node.right)
return leftRotate(node)
return node
function minValueNode(n):
cur = n
while cur.left != null:
cur = cur.left
return cur