All topics
76

The insert that rebalances itself

Tier 1Locked

Where it runs

1. The problem

Steps 72 to 75 gave you all the parts. Step 72 looks at a node that is off by 2 and names which of the four shapes it has (LL, LR, RL, RR). Steps 73 and 74 are the two single rotations that fix a node tilted to one side. Step 75 is the double rotation for the two zig-zags that one rotation cannot handle. What is left is to put them together into the operation you call: insert. An insert into an AVL tree is an ordinary BST insert plus one step. On the way back up you check every node you passed and rotate as soon as some node is off by 2. Then the tree never turns into the long chain that step 71 warned about, whatever order the data arrives in.

This step is part of the paid track

The first 33 steps are open to everyone: lesson, exercise and tests. This one opens with full access. Start with a free account and the free steps.

Create a free accountSee what is included

On LeetCode

Problems that keep a sorted set while values keep arriving, and need a quick search for a value or its nearest neighbour. JavaScript has no sorted set built in, and an AVL tree gives O(log n) insert and search even on sorted input.

We use necessary cookies to run the site (sign-in and language). If you accept, we also load Google Analytics to see which pages are used, and Google reCAPTCHA to keep spam off the contact and bug-report forms. Privacy policy