题目:给一个序列,判断该序列是否是一个二叉搜索树的后序遍历序列。是则返回true,否则返回false。
public boolean verifyPostorder(int[] postorder)
思路:
写一个bool recur(int[] postorder,int start,int end)递归函数,用二叉搜索树的性质来分割左右子树。只有左子树都小于root,右子树都大于root才行。然后分别递归左右子树。
注意:当没有左子树或没有右子树时,返回true的条件应该为start>=end,因为下一个end会比start小,自己举个例子就行了。
public boolean verifyPostorder(int[] postorder) {
return recur(postorder,0,postorder.length-1);
}
//树->大多为递归解法->考虑满二叉树,只有左子树或只有右子树的情况
//树的情况都考虑到了才能写完全
public boolean recur(int[] postorder, int start, int end) {
//有返回false的,当然也要有返回true
//要考虑左右子树缺少的情况
if(start >= end) return true;
int boundary = start;
while(postorder[boundary] < postorder[end]) boundary++;
for (int i = boundary; i < end; i++) {
if(postorder[i] < postorder[end]) return false;
}
return recur(postorder,start,boundary-1) && recur(postorder,boundary,end-1);
}