题目链接:
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 check(i:int,j:int) ->bool:
if i>j:
return True
k = i
while postorder[k]<postorder[j]:
k+=1
m =i
while postorder[k]>postorder[j]:
k+=1
return k==j and check(i,m-1) and check(m,j-1)
return check(0,len(postorder)-1)