Skip to main content

AVL tree for 24, 12, 8, 15, 35, ...

Short answer

Final AVL tree: root 24, left child 12 (left 8, right 15), right child 45 (left 35 with children 30 and 40, right 57 with right 78).

Create an AVL tree from the data: 24, 12, 8, 15, 35, 30, 57, 40, 45, 78.

Insert each key as in a BST and rebalance with rotations when a balance factor becomes ±2.

Balance factor of a node = height(left subtree) − height(right subtree). It must stay −1, 0 or +1. After each insertion, find the nearest unbalanced ancestor of the new node and fix it:

CaseWhere the new node wentFix
LLleft subtree of left childsingle right rotation
RRright subtree of right childsingle left rotation
LRright subtree of left childleft rotation on the child, then right rotation
RLleft subtree of right childright rotation on the child, then left rotation

Step-by-step insertion

StepInsertTree after step (root(left,right))Imbalance / rotation
12424balanced
21224(12,-)balanced
3812(8,24)at 24: LL: right rotate at 24
41512(8,24(15,-))balanced
53512(8,24(15,35))balanced
63024(12(8,15),35(30,-))at 12: RR: left rotate at 12
75724(12(8,15),35(30,57))balanced
84024(12(8,15),35(30,57(40,-)))balanced
94524(12(8,15),35(30,45(40,57)))at 57: LR: left at 40, right at 57
107824(12(8,15),45(35(30,40),57(-,78)))at 35: RR: left rotate at 35

Final AVL tree

24
├─L:12
│  ├─L:8
│  └─R:15
└─R:45
   ├─L:35
   │  ├─L:30
   │  └─R:40
   └─R:57
      └─R:78

Height = 4, and every node has balance factor −1, 0 or +1.

✓ Answer checked by Claude Opus 5.5 (high effort)

All Data Structure and Algorithm chapter 6 questions →