Skip to main content

AVL tree for 3, 2, 1, 4, 5, 6, 7, ...

Short answer

The final AVL tree has root 7, left child 4 (left child 2 with left 1 and right 3, right child 6 with left 5), and right child 15 (left child 13 with left 12 and right 14, right 16).

Construct an AVL tree for the following sequence of elements: 3, 2, 1, 4, 5, 6, 7, 16, 15, 14, 13, 12

Insert each key as in a BST and fix any node whose balance factor becomes ±2 by rotation.

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
133balanced
223(2,-)balanced
312(1,3)at 3: LL: right rotate at 3
442(1,3(-,4))balanced
552(1,4(3,5))at 3: RR: left rotate at 3
664(2(1,3),5(-,6))at 2: RR: left rotate at 2
774(2(1,3),6(5,7))at 5: RR: left rotate at 5
8164(2(1,3),6(5,7(-,16)))balanced
9154(2(1,3),6(5,15(7,16)))at 7: RL: right at 16, left at 7
10144(2(1,3),7(6(5,-),15(14,16)))at 6: RL: right at 15, left at 6
11137(4(2(1,3),6(5,-)),15(14(13,-),16))at 4: RR: left rotate at 4
12127(4(2(1,3),6(5,-)),15(13(12,14),16))at 14: LL: right rotate at 14

Final AVL tree

7
├─L:4
│  ├─L:2
│  │  ├─L:1
│  │  └─R:3
│  └─R:6
│     └─L:5
└─R:15
   ├─L:13
   │  ├─L:12
   │  └─R:14
   └─R:16

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 →