Imagine you have a singly linked list where all elements are arranged in perfect ascending order, like stepping stones across a river. Your mission is to transform this linear structure into a height-balanced binary search tree (BST).
A height-balanced BST is like a well-organized family tree where no branch is significantly longer than others - specifically, the depths of any two leaf nodes differ by at most 1. This ensures optimal search performance with O(log n) operations.
Input: Head of a sorted singly linked list
Output: Root of a height-balanced BST containing the same elements
The challenge lies in efficiently converting the linear structure while maintaining balance without using extra space for array conversion.
Input & Output
Time & Space Complexity
O(n) to convert list to array + O(n) to build BST = O(n) total
O(n) for array storage + O(log n) recursion stack = O(n) total
Constraints
-
The number of nodes in
headis in the range[0, 2 * 104] -
-105 โค Node.val โค 105 - The linked list is guaranteed to be sorted in ascending order
- Height-balanced means the depth of two leaf nodes should not differ by more than 1