simple python dfs way


  • 0
    K

    note that the order is build left subtree and right subtree and then return root

    class Solution:
        def constructMaximumBinaryTree(self, nums):
            """
            :type nums: List[int]
            :rtype: TreeNode
            """
    
            if len(nums)==1:
                return TreeNode(nums[0])
            
            root = TreeNode(max(nums))
            
            max_pos = nums.index(max(nums))
            
            
            if max_pos > 0:
                root.left = self.constructMaximumBinaryTree(nums[0: max_pos])
            
            if max_pos < len(nums)-1:
                root.right = self.constructMaximumBinaryTree(nums[max_pos+1: ])
            
            return root
    

Log in to reply
 

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