Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balanced binary search tree.
Example 1:
Input: head = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: One possible answer is [0,-3,9,-10,null,5], which represents the shown height balanced BST.
Input: head = []
Output: []
head is in the range [0, 2 * 104].The simplest way to address this problem is to transform the sorted linked list into an array. Once in array form, the middle element of any subarray serves as the root for the Binary Search Tree (BST). By recursively applying this process to the left and right subarrays, we build the complete tree.
This method is straightforward as it leverages the property of arrays that allow O(1) element access. However, this comes with a storage cost since we need additional space for the array.
Instead of first converting the linked list to an array, we can directly use the properties of the list and simulate an inorder traversal. By using the fast and slow pointer technique, we can find the middle element of the linked list and use it as the root. This method eliminates the need for extra space associated with array storage.
fast two steps and slow one step to maintain the alignment needed to find the middle.