题目

Given an integer array with no duplicates. A max tree building on this array is defined as follow:

The root is the maximum number in the array
The left subtree and right subtree are the max trees of the subarray divided by the root number.
Construct the max tree by the given array.

此题和Construct Binary Tree from Preorder and Inorder Traversal 很类似, 所以第一反应使用递归做。递归的解法过不了lintcode,会显示超时:

class Solution:
    """
    @param: A: Given an integer array with no duplicates.
    @return: The root of max tree.
    """
    def maxTree(self, A):
        def helper(A, start, end):
            if start > end:
                return None
            elif start == end:
                return TreeNode(A[start])
            maxVal = 0
            maxIndex = -1
            for i in range(start, end+1):
                if A[i] > maxVal:
                    maxVal, maxIndex = A[i], i
            root = TreeNode(maxVal)
            root.left = helper(A, start, maxIndex - 1)
            root.right = helper(A, maxIndex + 1, end)
            return root
        if A is None or len(A) == 0:
            return None
        return helper(A, 0, len(A)-1)

比递归的更好的方法是用stack,比较难想到,代码参考了:https://lefttree.gitbooks.io/...

思路是用一个单调递减栈寻找最大值。每遍历到一个新的数字A[i],我们就把比这个数字小的都弹栈,直到剩下比此数字大的数字。这个操作可以帮我们顺利找到左子树父节点。这个解法让我想到了经典的树的非递归遍历,需要再复习一下。

class Solution:
    """
    @param: A: Given an integer array with no duplicates.
    @return: The root of max tree.
    """
    def maxTree(self, A):
        stack = []
        for val in A:
            node = TreeNode(val)
            while len(stack) > 0 and val > stack[-1].val:
                node.left = stack.pop()
            if len(stack) > 0:
                stack[-1].right = node
            stack.append(node)
        return stack[0]

jocelynzz
1 声望0 粉丝

学习刷题专用博 ^_^