Skip to main content

AVL tree for month names

Short answer

Final AVL tree: root mar; left child jan with left aug (apr, feb with left dec) and right jun (left jul); right child oct with left may (right nov) and right sep.

Create an AVL tree for the following data: jan, feb, mar, apr, may, jun, jul, aug, sep, oct, nov, dec

Compare the month names in dictionary (alphabetical) order, so apr < aug < dec < feb < jan < jul < jun < mar < may < nov < oct < sep. Insert in the given order and rebalance 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
1janjanbalanced
2febjan(feb,-)balanced
3marjan(feb,mar)balanced
4aprjan(feb(apr,-),mar)balanced
5mayjan(feb(apr,-),mar(-,may))balanced
6junjan(feb(apr,-),mar(jun,may))balanced
7juljan(feb(apr,-),mar(jun(jul,-),may))balanced
8augjan(aug(apr,feb),mar(jun(jul,-),may))at feb: LR: left at apr, right at feb
9sepjan(aug(apr,feb),mar(jun(jul,-),may(-,sep)))balanced
10octjan(aug(apr,feb),mar(jun(jul,-),oct(may,sep)))at may: RL: right at sep, left at may
11novmar(jan(aug(apr,feb),jun(jul,-)),oct(may(-,nov),sep))at jan: RR: left rotate at jan
12decmar(jan(aug(apr,feb(dec,-)),jun(jul,-)),oct(may(-,nov),sep))balanced

Final AVL tree

mar
├─L:jan
│  ├─L:aug
│  │  ├─L:apr
│  │  └─R:feb
│  │     └─L:dec
│  └─R:jun
│     └─L:jul
└─R:oct
   ├─L:may
   │  └─R:nov
   └─R:sep

Height = 5, 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 →