AlgoFrames

Implement AVL insert

Challenge · Write code · about 30 min

Insert the distinct integers keys, in the given order, into an empty AVL tree and return its root.

After each insert, walk back up the path. At the first node whose subtree heights differ by more than 1, apply the standard fix: one rotation for the left-left and right-right cases, two rotations for the left-right and right-left cases. You may keep the heights in a map, since TreeNode has only val, left and right.

Example 1

Input:

[[10,20,30,40,50,25]]

Output:

[30,20,40,10,25,null,50]

Inserting 25 unbalances the root 20 (right-left case): rotate right at 40, then left at 20.

Example 2

Input:

[[3,1,2]]

Output:

[2,1,3]

3, 1, 2 is a zig-zag: rotate left at 1, then right at 3.

Constraints

  • 0 ≤ keys.length ≤ 1,000
  • -1,000 ≤ keys[i] ≤ 1,000
  • All keys are distinct

Learn the idea first: AVL trees and rotations, a visual lesson.

More AVL trees and rotations problems