leetcode-面试题33-二叉搜索树的后序遍历序列

 题目描述:

 

 方法一:递归 最坏O(N^2)

class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        def recur(i,j):
            if i >= j:return True
            p = i
            while postorder[p] < postorder[j] : p += 1
            m = p
            while postorder[p] > postorder[j] : p += 1
            return p == j and recur(i,m - 1) and recur(m,j - 1)

        return recur(0,len(postorder) - 1)

方法二:辅助单调栈 O(N)

class Solution:
    def verifyPostorder(self, postorder: List[int]) -> bool:
        stack ,root = [],float("inf")
        for i in range(len(postorder) - 1,-1, -1):
            if postorder[i] > root:return False
            while(stack and postorder[i] < stack[-1]):
                root = stack.pop()
            stack.append(postorder[i])
        return True

 

posted @ 2020-04-25 23:07  oldby  阅读(138)  评论(0编辑  收藏  举报