Simple python recursive solution , 10 line


  • 1
    B
        def sortedArrayToBST(self, nums):
            if len(nums)==0:
                return None
            elif len(nums)==1:
                return TreeNode(nums[0])
            else:
                mid=len(nums)//2
                node=TreeNode(nums[mid])
                node.left=self.sortedArrayToBST(nums[0:mid])
                node.right=self.sortedArrayToBST(nums[mid+1:len(nums)])
            return node

  • 1
    C

    Nice solution, while the code can be shorten as:

    def sortedArrayToBST(self, nums):
        if len(nums)==0:
            return None
        mid=len(nums)//2
        node=TreeNode(nums[mid])
        node.left=self.sortedArrayToBST(nums[0:mid])
        node.right=self.sortedArrayToBST(nums[mid+1:len(nums)])
        return node

  • 0

    Or, with a few more changes:

    def sortedArrayToBST(self, nums):
        if nums:
            mid=len(nums)/2
            node=TreeNode(nums[mid])
            node.left=self.sortedArrayToBST(nums[:mid])
            node.right=self.sortedArrayToBST(nums[mid+1:])
            return node

Log in to reply
 

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