Convert Sorted Array to Binary Tree

Problem

Given an array where elements are sorted in ascending order, convert it to a height balanced BST.

For this problem, a height-balanced binary tree is defined as a binary tree in which the depth of the two subtrees of every node never differ by more than 1.

For example:

Given the sorted array: [-10,-3,0,5,9],

One possible answer is: [0,-3,9,-10,null,5], which represents the following height balanced BST:

      0
     / \
   -3   9
   /   /
 -10  5

Solution

class Solution:
    def sortedArrayToBST(self, nums: List[int]) -> TreeNode:
        return self.helper(nums,0,len(nums)-1)    
    
    def helper(self,nums,low,high):
        if low > high:
            return None
        mid = low + ((high-low)//2)
        root = TreeNode(nums[mid])
        root.left = self.helper(nums,low, mid-1)
        root.right = self.helper(nums,mid+1,high)
        return root
        
#The middle of the array will be the root

#Time: O(n)
#Space:O(n) since we're doing recursion on array i
#think?

Last updated