Fast Python solution: 89 ms


  • 0
    M
    class Solution(object):
        def sortedArrayToBST(self, nums):
            if len(nums) == 0: return None
            rootIndex = int(len(nums)//2)
            root = TreeNode(nums[rootIndex])
            # which can speed up the code
            if len(nums) == 1: return root
            root.left = self.sortedArrayToBST(nums[0:rootIndex])
            root.right = self.sortedArrayToBST(nums[rootIndex+1:])
            return root

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.