Chapter 10 · Simulation

AVL Tree Simulator

← Chapter 10

Sample AVL tree loaded. Choose an operation.

Nodes0
Height0
Max |BF|0
Rotations0

Operation path

—

Rotation history

  1. No rotation needed.

AVL Tree Simulator

An AVL tree is a self-balancing binary search tree. Every node stores the height of its subtree, and its balance factor BF = height(left) − height(right) must always be −1, 0 or 1.

Controls

  • Type an integer and press Insert, Search or Delete. The path lights up first; then every rotation needed to restore balance is animated and logged in the rotation history.
  • Under each node you see its height (h) and balance factor (BF). Here height counts nodes (a leaf has h = 1), while the notes count edges, so every h shown is one more than in the notes; BF is the same either way. Validate checks the ordering, the stored heights and the balance.
  • Example, Random and Reset replace the tree; Stop interrupts a running animation.

AVL concepts

  • Stored heights: heights are updated on the way back up from a recursive insert or delete, and at every rotation.
  • Single rotation: a right rotation fixes an LL imbalance, a left rotation an RR imbalance.
  • Double rotation: in the LR and RL cases the heavy child leans the opposite way, so two rotations are needed.
  • Repair after deletion: a deletion can unbalance several ancestors, so the balance check continues all the way to the root.

AVL invariants

InvariantCondition
BST orderValues on the left are smaller, values on the right larger.
Correct stored height1 + max(left height, right height)
BalanceThe absolute value of the balance factor is at most 1.
DuplicatesDuplicate keys are rejected.

Because the height stays O(log n), search, insertion and deletion all run in O(log n) time.