Python Recursive Solution

  • 0
    class Solution(object):
        def constructMaximumBinaryTree(self, nums):
            :type nums: List[int]
            :rtype: TreeNode
            if not nums:
                return None
            def helper(node, nums):
                index = nums.index(max(nums))
                leftArr = nums[:index]
                rightArr = nums[index + 1:]
                if leftArr:
                    node.left = TreeNode(max(leftArr))
                    helper(node.left, leftArr)
                if rightArr:
                    node.right = TreeNode(max(rightArr))
                    helper(node.right, rightArr)
            root = TreeNode(max(nums))
            helper(root, nums)
            return root

Log in to reply

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