LintCode: Max Tree

题目

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]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值