Python 解LeetCode:654. Maximum Binary Tree

       用一个整型数组构建一个二叉树,根结点是数组中的最大值,左右子树分别是根结点的值在数组中左右两边的部分。

      分析,这是二叉树中比较容易想到的问题了,直接使用递归就行了,代码如下:

 1 class Solution(object):
 2     def constructMaximumBinaryTree(self, nums):
 3         """
 4         :type nums: List[int]
 5         :rtype: TreeNode
 6         """
 7         if not nums:
 8             return None
 9         max_value = max(nums)
10         max_index = nums.index(max_value)
11         root = TreeNode(max_value)
12         root.left = self.constructMaximumBinaryTree(nums[:max_index])
13         root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
14         return root

 

posted @ 2017-10-20 16:18  潇湘旧友  阅读(333)  评论(0编辑  收藏  举报