2019年2月28日 654. Maximum Binary Tree

比较简单的树拆分生成,我发现递归的思路我是比较有感觉的。。


# Definition for a binary tree node.
# class TreeNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

import operator

class Solution(object):
    
    def buildTree(self, nums):
        if len(nums) == 0:
            return None
        index, value = max(enumerate(nums), key=operator.itemgetter(1))
        
        root = TreeNode(value)
        root.left = self.buildTree(nums[:index])
        root.right = self.buildTree(nums[index+1:])
    
        return root

    
    def constructMaximumBinaryTree(self, nums):
        """
        :type nums: List[int]
        :rtype: TreeNode
        """
        return self.buildTree(nums)
posted @ 2019-02-28 08:54  miuc  阅读(84)  评论(0编辑  收藏  举报