Given an integer array nums
where the elements are sorted in ascending order, convert it to a height-balanced binary search tree (BST).
A height-balanced binary tree is a binary tree in which the depth of the two subtrees of every node never differs by more than one.
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:
To create a height-balanced binary search tree from a sorted array, we can recursively select the middle element of the current subarray as the root. This ensures that the tree remains balanced, as the left and right subarrays will have roughly the same size.
Here is the strategy:
None
.from typing import List, Optional
# 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 = right
def sortedArrayToBST(nums: List[int]) -> Optional[TreeNode]:
if not nums:
return None
mid = len(nums) // 2
root = TreeNode(nums[mid])
root.left = sortedArrayToBST(nums[:mid])
root.right = sortedArrayToBST(nums[mid+1:])
return root
The time complexity of this solution is ( O(n) ), where ( n ) is the number of elements in the input array. This is because each element is processed exactly once to create the BST nodes.
The space complexity is ( O(\log n) ) for the recursive call stack in an optimally balanced BST, but in the worst case of highly unbalanced BST (though this is balanced by definition), we might consider ( O(n) ) due to the depth of the recursion tree.
This implementation guarantees a height-balanced binary search tree formed from the sorted input array.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?