Let's solve this step by step, showing the tree after each insertion and any necessary rotations.
Starting with empty tree:
- Insert 10:
10 (BF: 0)
- Insert 20:
10 (BF: -1)
\
20 (BF: 0)
- Insert 5:
10 (BF: 0)
/ \
5 20
- Insert 41:
10 (BF: -1)
/ \
5 20 (BF: -1)
\
41
- Insert 19:
10 (BF: -1)
/ \
5 20 (BF: 0)
/ \
19 41
- Insert 7:
Before rotation:
10 (BF: 2)
/ \
5 20
\ / \
7 19 41
After LL rotation at 5:
10 (BF: 0)
/ \
7 20
/ / \
5 19 41
- Insert 43:
10 (BF: -1)
/ \
7 20 (BF: -1)
/ / \
5 19 41 (BF: -1)
\
43
- Insert 40:
Before rotation:
10
/ \
7 20
/ / \
5 19 41
/ \
40 43
After rotation (RR case at 41):
10
/ \
7 20
/ / \
5 19 41
/ \
40 43
- Insert 50:
10 (BF: -2)
/ \
7 20 (BF: -2)
/ / \
5 19 41
/ \
40 43
\
50
Needs rebalancing! After rotations:
20
/ \
10 41
/ \ / \
7 19 40 43
/ \
5 50
- Finally, insert 45:
20
/ \
10 41
/ \ / \
7 19 40 43
/ / \
5 45 50
Final AVL tree is balanced with all balance factors between -1 and 1.
Key points in this insertion sequence:
- We needed rotations after inserting 7 (LL case)
- Major rebalancing occurred after inserting 50 (multiple rotations needed)
- The final tree maintains AVL properties with height difference ≤ 1 for all nodes
Would you like me to explain any of the rotation steps in more detail?