Description
Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced BST. Return the result as an array.
Examples
Input:
head = [-10,-3,0,5,9]Output:
[0,-3,9,-10,null,5]Explanation:
Middle element 0 becomes root. Left subtree from [-10,-3], right from [5,9]. Recursively balance.
Input:
head = []Output:
[]Explanation:
An empty list converts to an empty BST (null).
Input:
head = [1,3,5,7,9,11]Output:
[7,3,11,1,5,9]Explanation:
For an even number of nodes, choosing the second middle element (5) as root. The left subtree contains [1,3] with 3 as root, and right subtree contains [7,9,11] with 9 as root, creating a height-balanced BST.
Constraints
- •
0 ≤ nodes ≤ 2 × 10⁴