Skip to main content

AVL Tree

SpaceTime
AccessLookupInsertionDeletion
O(n)O(log n)O(log n)O(log n)O(log n)

Definition​

AVL Tree is a self-balancing binary search tree that ensures the heights of its 2 child subtrees differ by at most one.

Simplified

Binary AVL Tree is like a special bookshelf. It organizes data (like books) in a way that you can quickly find, add, or remove items. Each item can have 2 others next to it, one smaller and one bigger. The shelf stays balanced by ensuring the difference in the number of items on either side of any item is not more than one.

Practice​

AspectPseudo Code
Insertion
insert(node, key):
if node == ø:
return createNewNode(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 // Duplicate keys are not allowed

node.height = 1 + max(height(node.left), height(node.right)) // Update height

return rebalance(node) // Perform rotations to maintain balance
Rebalance
rebalance(node):
balance = get_balance(node)

if balance > 1: // Left Heavy
if get_balance(node.left) < 0: // Left-Right Case
node.left = left_rotate(node.left)
return right_rotate(node)

if balance < -1: // Right Heavy
if get_balance(node.right) > 0: // Right-Left Case
node.right = right_rotate(node.right)
return left_rotate(node)

return node

left_rotate(y):
x = y.right
T2 = x.left
x.left = y
y.right = T2
y.height = 1 + max(height(y.left), height(y.right))
x.height = 1 + max(height(x.left), height(x.right))
return x

right_rotate(x):
y = x.left
T2 = y.right
y.right = x
x.left = T2
x.height = 1 + max(height(x.left), height(x.right))
y.height = 1 + max(height(y.left), height(y.right))
return y
Height
height(node):
if node == ø:
return 0
return node.height
Get Balance
get_balance(node):
if node == ø:
return 0
return height(node.left) - height(node.right)
Search
search(node, key):
if node == ø or key == node.key:
return node
if key < node.key:
return search(node.left, key)
return search(node.right, key)
Find MIN
find_min(node):
while node.left != ø:
node = node.left
return node
Find MAX
find_max(node):
while node.right != ø:
node = node.right
return node