/109. Convert Sorted List to Binary Search Tree

109. Convert Sorted List to Binary Search Tree

Medium
Linked Lists66.1% acceptance

Given the head node of a singly linked list with integer values sorted in ascending order, construct a height-balanced binary search tree (BST) containing all values from the list. Return the root node of the BST. The BST should be height-balanced, meaning the depth difference between left and right subtrees of any node is at most one. The output should be represented as a level-order traversal list of node values, using None for missing children.

Example 1

Input: ListNode(1, ListNode(2, ListNode(3, ListNode(4))))

Output: [2, 1, 3, None, None, None, 4]

Explanation: The BST is height-balanced with root 2, left child 1, right child 3, and right child of 3 is 4.

Example 2

Input: ListNode(-5, ListNode(-2, ListNode(0, ListNode(3, ListNode(8)))))

Output: [0, -5, 3, None, -2, None, 8]

Explanation: The BST is height-balanced with root 0, left subtree -5 -> -2, right subtree 3 -> 8.

Constraints

  • 0 <= number of nodes in input_list <= 20000
  • -100000 <= node_value <= 100000
  • Input list is sorted in ascending order
Python (current runtime)

Case 1

Input: ListNode(7, ListNode(8, ListNode(9)))

Expected: [8, 7, 9]

Case 2

Input: ListNode(-1, ListNode(0, ListNode(1, ListNode(2, ListNode(3)))))

Expected: [1, 0, 2, -1, None, None, 3]

Case 3

Input: None

Expected: []

Case 4

Input: ListNode(5)

Expected: [5]