33、二叉树的后序遍历序列

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true,否则返回 false。假设输入的数组的任意两个数字都互不相同。

参考以下这颗二叉搜索树:

5
/
2 6
/
1 3
示例 1:

输入: [1,6,3,2,5]
输出: false

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 stack[-1] > postorder[i]:
                root = stack.pop()
            stack.append(postorder[i])
        return True
            
原文地址:https://www.cnblogs.com/liushoudong/p/13626767.html