My DFS Python Solution beats 82%


  • 0
    D
    class Solution(object):
        def sortedArrayToBST(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
            if not nums:
                return None
            root = self.dfs(nums, 0, len(nums) - 1)
            return root
    
        def dfs(self, nums, start, end):
            if start > end:
                return None
            if start == end:
                return TreeNode(nums[start])
            mid = start + (end - start) / 2
            root = TreeNode(nums[mid])
            root.left = self.dfs(nums, start, mid - 1)
            root.right = self.dfs(nums, mid + 1, end)
            return root

Log in to reply
 

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