Given an integer array with no duplicates. A maximum tree building on this array is defined as follow:
The root is the maximum number in the array.
The left subtree is the maximum tree constructed from left part subarray divided by the maximum number.
The right subtree is the maximum tree constructed from right part subarray divided by the maximum number.
Construct the maximum tree by the given array and output the root node of this tree.
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
if not nums:
return None
root = TreeNode(max(nums))
maxIndex = nums.index(max(nums))
root.left = self.constructMaximumBinaryTree(nums[:maxIndex])
root.right = self.constructMaximumBinaryTree(nums[maxIndex+1:])
return root
1 构建一个binary tree,分为3步,第一步建立root,第二步建立左子树,第二步建立右子树
2 下面的就再进行递归就ok了
3 还有一个关键点是找到max的position