Given an integer array nums where the elements are sorted in ascending order, convert it to a height-balancedbinary search tree.
Example 1:
Input: nums = [-10,-3,0,5,9]
Output: [0,-3,9,-10,null,5]
Explanation: [0,-10,5,null,-3,null,9] is also accepted:
Example 2:
Input: nums = [1,3]
Output: [3,1]
Explanation: [1,null,3] and [3,1] are both height-balanced BSTs.
Constraints:
1 <= nums.length <= 104
-104 <= nums[i] <= 104
nums is sorted in a strictly increasing order.
Solutions
Solution 1: Binary Search + Recursion
We design a recursive function $\textit{dfs}(l, r)$, which represents that the values of the nodes to be constructed in the current binary search tree are within the index range $[l, r]$ of the array $\textit{nums}$. This function returns the root node of the constructed binary search tree.
The execution process of the function $\textit{dfs}(l, r)$ is as follows:
If $l > r$, it means the current array is empty, so return null.
If $l \leq r$, take the element at index $\textit{mid} = \lfloor \frac{l + r}{2} \rfloor$ of the array as the root node of the current binary search tree, where $\lfloor x \rfloor$ denotes the floor function of $x$.
Recursively construct the left subtree of the current binary search tree, with the root node's value being the element at index $\textit{mid} - 1$ of the array. The values of the nodes in the left subtree are within the index range $[l, \textit{mid} - 1]$ of the array.
Recursively construct the right subtree of the current binary search tree, with the root node's value being the element at index $\textit{mid} + 1$ of the array. The values of the nodes in the right subtree are within the index range $[\textit{mid} + 1, r]$ of the array.
Return the root node of the current binary search tree.
The answer is the return value of the function $\textit{dfs}(0, n - 1)$.
The time complexity is $O(n)$, and the space complexity is $O(\log n)$. Here, $n$ is the length of the array $\textit{nums}$.
1 2 3 4 5 6 7 8 9101112131415
# 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:defsortedArrayToBST(self,nums:List[int])->Optional[TreeNode]:defdfs(l:int,r:int)->Optional[TreeNode]:ifl>r:returnNonemid=(l+r)>>1returnTreeNode(nums[mid],dfs(l,mid-1),dfs(mid+1,r))returndfs(0,len(nums)-1)
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */funcsortedArrayToBST(nums[]int)*TreeNode{vardfsfunc(int,int)*TreeNodedfs=func(l,rint)*TreeNode{ifl>r{returnnil}mid:=(l+r)>>1return&TreeNode{nums[mid],dfs(l,mid-1),dfs(mid+1,r)}}returndfs(0,len(nums)-1)}