DSA AVL Trees
Language: Data Structures
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
self.height = 1 # height of a leaf is 1
def height(node):
return node.height if node else 0
def balance_factor(node):
return height(node.left) - height(node.right)
def update_height(node):
node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(y):
x = y.left
t2 = x.right
x.right = y
y.left = t2
update_height(y)
update_height(x)
return x # x is the new subtree root
def rotate_left(x):
y = x.right
t2 = y.left
y.left = x
x.right = t2
update_height(x)
update_height(y)
return y # y is the new subtree root
# Manually build a left-left heavy case: 30 with left child 20,
# which itself has left child 10.
root = Node(30)
root.left = Node(20)
root.left.left = Node(10)
update_height(root.left)
update_height(root)
print(balance_factor(root)) # 2 - unbalanced
root = rotate_right(root) # fix it with a single right rotation
print(root.value, root.left.value, root.right.value) # 20 10 30
print(balance_factor(root)) # 0 - balanced againOutput
Click Run to execute this code.