Given the head of a singly linked list where elements are sorted in ascending order, convert it to a height-balancedbinary 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.
Example 2:
Input: head = []
Output: []
Constraints:
The number of nodes in head is in the range [0, 2 * 104].
-105 <= Node.val <= 105
Solutions
Solution 1: DFS
We first convert the linked list to an array \(\textit{nums}\), and then use depth-first search to construct the binary search tree.
We define a function \(\textit{dfs}(i, j)\), where \(i\) and \(j\) represent the current interval \([i, j]\). Each time, we choose the number at the middle position \(\textit{mid}\) of the interval as the root node, recursively construct the left subtree for the interval \([i, \textit{mid} - 1]\), and the right subtree for the interval \([\textit{mid} + 1, j]\). Finally, we return the node corresponding to \(\textit{mid}\) as the root node of the current subtree.
In the main function, we just need to call \(\textit{dfs}(0, n - 1)\) and return the result.
The time complexity is \(O(n)\), and the space complexity is \(O(n)\). Here, \(n\) is the length of the linked list.
1 2 3 4 5 6 7 8 910111213141516171819202122232425
# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = next# Definition for a binary tree node.# class TreeNode:# def __init__(self, val=0, left=None, right=None):# self.val = val# self.left = left# self.right = rightclassSolution:defsortedListToBST(self,head:Optional[ListNode])->Optional[TreeNode]:defdfs(i:int,j:int)->Optional[TreeNode]:ifi>j:returnNonemid=(i+j)>>1l,r=dfs(i,mid-1),dfs(mid+1,j)returnTreeNode(nums[mid],l,r)nums=[]whilehead:nums.append(head.val)head=head.nextreturndfs(0,len(nums)-1)
/** * Definition for singly-linked list. * type ListNode struct { * Val int * Next *ListNode * } *//** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsortedListToBST(head*ListNode)*TreeNode{nums:=[]int{}for;head!=nil;head=head.Next{nums=append(nums,head.Val)}vardfsfunc(i,jint)*TreeNodedfs=func(i,jint)*TreeNode{ifi>j{returnnil}mid:=(i+j)>>1left:=dfs(i,mid-1)right:=dfs(mid+1,j)return&TreeNode{nums[mid],left,right}}returndfs(0,len(nums)-1)}