Implement rotate-right
Standard · Write code · about 10 min
Rotate the BST with root x to the right and return the new root. The left child y of x moves up, x becomes the right child of y, and the old right subtree of y becomes the left subtree of x.
If x is null or has no left child, return x unchanged.
Example 1
Input:
[[20,10,30,5,15]]
Output:
[10,5,20,null,null,15,30]
20 moves down and its left child moves up.
Example 2
Input:
[[2,1]]
Output:
[1,null,2]
Two nodes swap roles.
Constraints
- 0 ≤ number of nodes ≤ 1,000
- -1,000 ≤ key ≤ 1,000
- The tree is a valid BST, given in level order; null marks a missing child
Learn the idea first: AVL trees and rotations, a visual lesson.
More AVL trees and rotations problems
- Identify the rotation Warm-up
- Spot the unbalanced node Warm-up
- Insert and rebalance Standard
- Implement rotate-left Standard
- Implement AVL insert Challenge