Python Simple DFS


  • 2
    def constructMaximumBinaryTree(self, nums):   
        dummy = TreeNode(None)
        def d(root, nums):
            if not nums:
                return 
            i = nums.index(max(nums))
            root.val = max(nums)
            if nums[:i]:
                root.left = TreeNode(None)
                d(root.left, nums[:i])
            if nums[i+1:]:
                root.right = TreeNode(None)
                d(root.right, nums[i+1:])
        d(dummy, nums)
        return dummy

  • 9

    Could be shorter.

    class Solution(object):
        def constructMaximumBinaryTree(self, nums):
            if nums:
                pos = nums.index(max(nums))
                root = TreeNode(nums[pos])
                root.left = self.constructMaximumBinaryTree(nums[:pos])
                root.right = self.constructMaximumBinaryTree(nums[pos+1:])
                return root
    

  • 0
    M

    Thanks a lot!


Log in to reply
 

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