剑指 Offer 33. 二叉搜索树的后序遍历序列
思路
参考 面试题33. 二叉搜索树的后序遍历序列(递归分治 / 单调栈,清晰图解) - 二叉搜索树的后序遍历序列 - 力扣(LeetCode) (leetcode-cn.com)
后序遍历的特点就是当前数组区间的最后一个元素就是根节点,如何找到左右子树的区间呢,从左到右遍历,找到第一个大于根节点的节点,该节点之前都是左子树,其余为右子树。
判断是否是后序遍历,只需判断从找到的右子树起点开始是否都大于根节点。
然后再对左右子树各自判断是否满足后序遍历
代码
class Solution {
public boolean verifyPostorder(int[] postorder) {
return helper(postorder,0,postorder.length-1);
}
public boolean helper(int[] postorder,int l,int r){
if(l>=r)return true;
int i=l;
while(postorder[i]<postorder[r]) i++;
int m=i;
while(postorder[i]>postorder[r]) i++;
return i==r&&helper(postorder,l,m-1)&&helper(postorder,m,r-1);
}
}