Skip to contentKEEP THE CRAFTTHE SANCTUARY

Sorted List to Balanced BST

Turn a sorted linked list into a height-balanced binary search tree.

The problem

Implement Solution.sortedListToBST(head). The linked list is sorted in ascending order. Build a height-balanced binary search tree that holds the same values and return its root; height-balanced means that at every node, the heights of the left and right subtrees differ by at most one. Use the middle value of a range as the root of that range. When the range has an even number of values, use the lower of the two middle values: for 1 -> 2 -> 3 -> 4 the root is 2. Return None for an empty list. The list has at most 20,000 nodes, and values are between -100,000 and 100,000.

Starter code

class Solution:
    def sortedListToBST(self, head):
        pass

Public examples

  1. head = [-10, -3, 0, 5, 9]gives[0, -10, 5, None, -3, None, 9]
  2. head = [1, 2, 3]gives[2, 1, 3]
  3. head = [1, 2, 3, 4]gives[2, 1, 3, None, None, None, 4]

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

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