题目描述:
思路:对于从二叉树的遍历还原为树一直不太明白,好在看了大神的解答清晰了很多。二叉搜索树的后序遍历是有顺序的,第一个大于根节点的值就是右子树的开始,这样就可以将整个数组分为三部分:左子树(都小于根),右子树(都大于根),根。之后判断左子树内元素是否都小于根,右子树是否都大于根。之后递归查看左子树和右子树。当只有一个节点时(左>=右时),结束递归。
class Solution {
public boolean verifyPostorder(int[] postorder) {
return rec(postorder,0,postorder.length-1);
}
private boolean rec(int[] postorder,int left,int right){
if(left>=right)return true;
int p=left;
while(postorder[p]<postorder[right]){
p++;
}
int m=p;
while(postorder[p]>postorder[right]){
p++;
}
return p==right&&rec(postorder,left,m-1)&&rec(postorder,m,right-1);
}
}