Convert Sorted List to Binary Search Tree

Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.

Return the root of the resulting height-balanced binary search tree.

Example 1
[-10] -> [-3] -> [0] -> [5] -> [9] -> null
---
      0
     / \
   -3   9
   /   /
 -10  5
Inputhead = [-10,-3,0,5,9]
Output[0,-3,9,-10,null,5]
One possible answer is [0,-3,9,-10,null,5], which represents a height-balanced BST built from the sorted list.
Example 2
null
---
null
Inputhead = []
Output[]
An empty linked list converts to an empty binary search tree.

Constraints

  • The number of nodes in head is in the range [0, 2 * 10^4].
  • -10^5 <= Node.val <= 10^5

Asked at 9 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate