题目链接:https://leetcode-cn.com/problems/er-cha-sou-suo-shu-de-hou-xu-bian-li-xu-lie-lcof/
难度:中等
描述:
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。
题解
class Solution:
def verifyPostorder(self, postorder: List[int]) -> bool:
def recursion(left, right):
if left >= right:
return True
i = left
while postorder[i] < postorder[right]:
i += 1
mid = i - 1
while postorder[i] > postorder[right]:
i += 1
return i == right and recursion(left, mid) and recursion(mid+1, right-1)
return recursion(0, len(postorder)-1)