Skip to contentKEEP THE CRAFTTHE SANCTUARY

Recognize Three-Node Tree Rotations

See what every AVL rotation case does to three inserted values: single or double, the median always ends up as the root.

The problem

Insert three distinct values, one after another, into an empty binary search tree. Unless the first value is the median, you get a chain of three nodes, and an AVL tree repairs it with a rotation: - a straight chain (left-left or right-right) needs a single rotation; - a zigzag (left-right or right-left) needs a double rotation. Implement balance_three_nodes(insertion_order). insertion_order holds exactly three distinct values that can be compared with each other. Return [root, left_child, right_child] of the balanced tree after the rotation. If the first value is already the median, the tree is balanced as inserted. Examples: [1, 2, 3] forms a right-right chain, and a left rotation at 1 gives [2, 1, 3]. [3, 1, 2] forms a left-right zigzag (1 is the left child of 3, and 2 is the right child of 1); rotating left at 1 and then right at 3 also gives [2, 1, 3].

Starter code

def balance_three_nodes(insertion_order):
    pass

Public examples

  1. insertion_order = [1, 2, 3]gives[2, 1, 3]
  2. insertion_order = [3, 1, 2]gives[2, 1, 3]

Solving it in the practice book needs an active paid plan.

Open it in the practice book
One thought at a time.