Keep the branches in balance.
Understand height balance and implement a rebalancing insertion.
01 Model the idea
An AVL tree maintains a height difference of at most one between each node’s subtrees. Insertion first follows ordinary BST ordering, then updates heights and performs rotations when a balance factor leaves the allowed range. Single and double rotations restore the invariant while preserving in-order key order. This makes search, insertion, and deletion logarithmic in a correctly implemented AVL tree; the exercise implements insertion only.
At every node, subtree heights differ by at most one.
02 State the strategy
Read the steps independently of syntax. Explain what each step preserves before translating it into code.
INSERT using BST order
UPDATE heights on the return path
IF unbalanced: rotate child if necessary, then rotate subtree root03 Make it concrete
The implementation uses Python 3.11+ with only the standard library. Run it locally, or download the independent DSA workbench.
class Node:
def __init__(self, value):
self.value, self.left, self.right, self.height = value, None, None, 1
def height(node): return node.height if node else 0
def update(node): node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(root):
child = root.left
root.left, child.right = child.right, root
update(root); update(child)
return child
def rotate_left(root):
child = root.right
root.right, child.left = child.left, root
update(root); update(child)
return child
def insert(root, value):
if root is None: return Node(value)
if value < root.value: root.left = insert(root.left, value)
elif value > root.value: root.right = insert(root.right, value)
else: return root
update(root)
balance = height(root.left) - height(root.right)
if balance > 1:
if value > root.left.value: root.left = rotate_left(root.left)
return rotate_right(root)
if balance < -1:
if value < root.right.value: root.right = rotate_right(root.right)
return rotate_left(root)
return root
root = None
for value in [30, 20, 10]: root = insert(root, value)
print(root.value, root.height)20 2
- 1
A leaf height is one and an absent child height is zero. Update heights after changing links, and update the old root before the new root during rotation.
- 2
The left-right and right-left cases require rotating the child first. A single outer rotation then restores balance.
- 3
The short fixture triggers a left-left imbalance. Real tests should include all four rotation cases and recursively verify sorted order, stored heights, and balance factors after every insertion.
04 Count the cost
O(log n) search and insertion when the invariant is maintained
O(log n) insertion stack; O(n) nodes
Bounds refer to the shown implementation and exclude printed output unless stated. n is input size; V and E are graph vertices and edges.
05 Your next move
Test the four three-key rotation cases and verify that each final root is 20. Use the lesson’s insertion functions, then add a recursive invariant checker.
Reveal one possible solution +
class Node:
def __init__(self, value):
self.value, self.left, self.right, self.height = value, None, None, 1
def height(node): return node.height if node else 0
def update(node): node.height = 1 + max(height(node.left), height(node.right))
def rotate_right(root):
child = root.left
root.left, child.right = child.right, root
update(root); update(child)
return child
def rotate_left(root):
child = root.right
root.right, child.left = child.left, root
update(root); update(child)
return child
def insert(root, value):
if root is None: return Node(value)
if value < root.value: root.left = insert(root.left, value)
elif value > root.value: root.right = insert(root.right, value)
else: return root
update(root)
balance = height(root.left) - height(root.right)
if balance > 1:
if value > root.left.value: root.left = rotate_left(root.left)
return rotate_right(root)
if balance < -1:
if value < root.right.value: root.right = rotate_right(root.right)
return rotate_left(root)
return root
def check(node, low=float('-inf'), high=float('inf')):
if node is None: return 0
assert low < node.value < high
left = check(node.left, low, node.value)
right = check(node.right, node.value, high)
assert abs(left - right) <= 1
assert node.height == 1 + max(left, right)
return node.height
for values in [[30,20,10], [10,20,30], [30,10,20], [10,30,20]]:
root = None
for value in values:
root = insert(root, value)
check(root)
assert root.value == 20
print("Four rotation cases and invariants passed")06 Check your reasoning
What invariant does an AVL tree maintain?
Understand it. Then own it.
Can you explain the invariant, trace an edge case, and defend the cost model? Log the experiment when the reasoning makes sense.