BALT-P2

Rotate at a key

Practice 2 of 6Balanced trees8 tests

The problem

You are given the root of a binary search tree, a key that is in the tree, and a side, 'left' or 'right'. Do that rotation (lesson 2) at the node holding the key, and return the root of the whole tree.

#        6                    4
#       / \                  / \
#      4   7       ->       2   6
#     / \                      / \
#    2   5                    5   7
rotate(root, 6, 'right')     # returns the node 4

A right rotation lifts the node’s left child; a left rotation lifts its right child. The child that comes up is always there. If the node has a parent, the parent must now point to the child that came up. Move the existing nodes; do not build new ones.

The tests write a tree as a level-order list: the values level by level, left to right, with None where a child is missing. So [3, 9, 20, None, None, 15, 7] is 3 with children 9 and 20, where 20 has children 15 and 7. An empty tree is None.

Limits

  • Up to 50,000 nodes; all keys are different.

Builds on BALT-2 Rotations.

Continue on a laptop

Practice runs Python in the browser and needs a keyboard and a wider screen. Read the problem and open hints here, then write your solution on a laptop. Progress is saved per browser for now, so hints opened here stay on this device.

Need a hint?0 of 3 opened

  1. Hint 1Nudge
  2. Hint 2Approach Open hint 1 first
  3. Hint 3Pseudocode Open hint 2 first
  4. Worked solutionlast resort Opens after all 3 hints
Python waits for a wider screensolution.py

Ctrl + Enter runs the tests. Tab indents; press Esc, then Tab, to leave the editor.

8 tests, not run yet
Test results
#TestResultReads · time
1Right at the rootNot run
2Left at the rootNot run
3A left child, deeper downNot run
4A right child, deeper downNot run
5Right, near a leafNot run
6Same nodesNot run
7There and backNot run
850,000 nodesNot run