- 2074 Bhadra · 6 marks
AVL tree for 10 20 30 50 45 40 8 5 3
Short answer
After insertions with rotations, the final AVL tree has root 30, left child 10 (left child 5 with left 3 and right 8, right child 20), and right child 45 (left 40, right 50). All balance factors are -1,0,+1.
Create an AVL balanced tree for data sequence 10 20 30 50 45 40 8 5 3.
Insert the keys one by one like in a BST, then rebalance with rotations whenever 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:
| Case | Where the new node went | Fix |
|---|---|---|
| LL | left subtree of left child | single right rotation |
| RR | right subtree of right child | single left rotation |
| LR | right subtree of left child | left rotation on the child, then right rotation |
| RL | left subtree of right child | right rotation on the child, then left rotation |
Step-by-step insertion
| Step | Insert | Tree after step (root(left,right)) | Imbalance / rotation |
|---|---|---|---|
| 1 | 10 | 10 | balanced |
| 2 | 20 | 10(-,20) | balanced |
| 3 | 30 | 20(10,30) | at 10: RR: left rotate at 10 |
| 4 | 50 | 20(10,30(-,50)) | balanced |
| 5 | 45 | 20(10,45(30,50)) | at 30: RL: right at 50, left at 30 |
| 6 | 40 | 30(20(10,-),45(40,50)) | at 20: RL: right at 45, left at 20 |
| 7 | 8 | 30(10(8,20),45(40,50)) | at 20: LL: right rotate at 20 |
| 8 | 5 | 30(10(8(5,-),20),45(40,50)) | balanced |
| 9 | 3 | 30(10(5(3,8),20),45(40,50)) | at 8: LL: right rotate at 8 |
Final AVL tree
30
├─L:10
│ ├─L:5
│ │ ├─L:3
│ │ └─R:8
│ └─R:20
└─R:45
├─L:40
└─R:50
Height = 4, and every node has balance factor −1, 0 or +1.
✓ Answer checked by Claude Opus 5.5 (high effort)
Related questions
- AVL tree for 10, 20, 30, 35, 50, ... · Data Structure and Algorithm, chapter 6
- AVL tree for 24, 12, 8, 15, 35, ... · Data Structure and Algorithm, chapter 6
- AVL tree for 52, 65, 72, 15, 11, 32, 20 · Data Structure and Algorithm, chapter 6
- AVL tree for month names · Data Structure and Algorithm, chapter 6 · asked 2×
- B-tree insertion algorithm; AVL of months · Data Structure and Algorithm, chapter 6 · asked 2×
- AVL tree for 3, 2, 1, 4, 5, 6, 7, ... · Data Structure and Algorithm, chapter 6
- Elliptic: 2x2 grid 10/20/40/50 · Numerical Method, chapter 7 · asked 5×