Maximum Binary Tree
此题和利用前序加中序序列构建二叉树那道题类似,都是利用三个坐标去限定范围,再利用递归逐渐缩小范围最后完成构建,值得注意的是base case的判断条件,只要左右有一边的范围没有非法,我们就还需要继续向下构建子树,除非两边都非法了,这样才返回空节点,时间复杂度为O(n^2)
class Solution(object):
def constructMaximumBinaryTree(self, nums):
"""
:type nums: List[int]
:rtype: TreeNode
"""
return self.buildTree(nums, 0, nums.index(max(nums)), len(nums) - 1)
def buildTree(self, nums, start, rootIndex, end):
if start > rootIndex and end < rootIndex:
return None
left, right = None, None
root = TreeNode(nums[rootIndex])
if start < rootIndex:
root.left = self.buildTree(nums, start, nums.index(max(nums[start : rootIndex])), rootIndex - 1)
if end > rootIndex:
root.right = self.buildTree(nums, rootIndex + 1, nums.index(max(nums[rootIndex + 1 : end + 1])), end)
return root