Another 8-line Python with explanation


  • 0

    Idea: use the median number to split the given nums array by half until it is not splittable. When returning, we get left sub-tree and right sub-tree and return it to the up-level recursion.

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

Log in to reply
 

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