
Sponsored
Sponsored
This approach involves converting the linked list to an array and then using the middle of the array to create a height-balanced binary search tree (BST). The middle of the array will become the root, and this concept is applied recursively to the left and right halves of the array.
Time Complexity: O(n), where n is the number of nodes in the linked list, because we traverse the list to create the array.
Space Complexity: O(n), for storing the values in the array.
1class ListNode:
2 def __init__(self, val=0, next=None):
3 self.val = val
4 self.next = next
5
6class TreeNode:
7 def __init__(self, val=0, left=None, right=None):
8 self.val = val
9 self.left = left
10 self.right = right
11
12class Solution:
13 def sortedListToBST(self, head: ListNode) -> TreeNode:
14 values = []
15 while head:
16 values.append(head.val)
17 head = head.next
18
19 def convertListToBST(left, right):
20 if left > right:
21 return None
22
23 mid = (left + right) // 2
24 node = TreeNode(values[mid])
25
26 if left == right:
27 return node
28
29 node.left = convertListToBST(left, mid - 1)
30 node.right = convertListToBST(mid + 1, right)
31 return node
32
33 return convertListToBST(0, len(values) - 1)The solution first converts the linked list into an array for easy access. It then uses the middle element of the array as the root of the BST and recursively applies this method to the left and right segments of the list. This way, a height-balanced BST is created.
This approach uses the slow and fast pointer technique to find the middle of the linked list, which forms the root of the BST. The linked list is recursively divided into two halves, and this method is used to create the left and right subtrees.
Time Complexity: O(n log n), because cutting the list in half at each step takes O(log n) splits, and each split involves a linear scan.
Space Complexity: O(log n), for the recursion stack where n is the number of nodes in the list.
1class ListNode {
2 int val;
The Java solution uses a recursive function, with fast and slow pointers to find the middle of the linked list. This middle element becomes the root of the BST, and the process is applied to the list segments left and right of the middle to form the subtrees.