654. Maximum Binary Tree

从数列最大的数,左列放在左边,右边最大放在右边

Input: [3,2,1,6,0,5]
Output: return the tree root node representing the following tree:

      6
    /   \
   3     5
    \    / 
     2  0   
       \
        1
Note:
The size of the given array will be in the range [1,1000].

递归,主要是索引数组最大数:

class Solution(object):
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        def Nod(nums):
            start = 0
            end = len(nums)-1
            if start>end:
                return None
            max_num = max(nums)
            max_code = nums.index(max_num)
            node = TreeNode(max_num)
            left_nums = nums[:max_code]
            right_nums = nums[max_code+1:]
            node.left = Nod(left_nums)
            node.right = Nod(right_nums)
            return node
        return Nod(nums)

你可能感兴趣的:(654. Maximum Binary Tree)