AlgoFrames

Implement rotate-left

Standard · Write code · about 10 min

Rotate the BST with root x to the left and return the new root. The right child y of x moves up, x becomes the left child of y, and the old left subtree of y becomes the right subtree of x.

If x is null or has no right child, return x unchanged.

Example 1

Input:

[[10,5,20,null,null,15,30]]

Output:

[20,10,30,5,15]

10 moves down and its right child moves up.

Example 2

Input:

[[1,null,2]]

Output:

[2,1]

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