用一个整型数组构建一个二叉树,根结点是数组中的最大值,左右子树分别是根结点的值在数组中左右两边的部分。
分析,这是二叉树中比较容易想到的问题了,直接使用递归就行了,代码如下:
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
max_value = max(nums)
max_index = nums.index(max_value)
root = TreeNode(max_value)
root.left = self.constructMaximumBinaryTree(nums[:max_index])
root.right = self.constructMaximumBinaryTree(nums[max_index+1:])
return root