输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历结果。如果是则返回 true
,否则返回 false
。假设输入的数组的任意两个数字都互不相同。如输入: [1,6,3,2,5] ,输出: false。
如果一棵树是二叉搜索树,则对每一个非叶子节点来讲,其左节点肯定小于该节点,其右节点的值大于该节点。设输入的后续遍历数组为postorder,数组长度为n,则其最后一个节点肯定是根节点。从左到右对数组进行遍历,找到连续的小于postorder[n-1]的节点,假设前i个元素均小于postorder[n-1],如果右边的节点还有小于postorder[n-1]的节点,则肯定不是二叉搜索树。再对[0,i-1]进行遍历,检查是否满足二叉搜索树,右子树也类似。一次递归调用,如果所有的子树均满足二叉搜索树,则该整数数组是某二叉搜索树的后续遍历结果。
package leecodeOff;
/*
* 33.二叉搜索树的后序遍历实现
*/
public class Demo33 {
public boolean verifyPostorder(int[] postorder) {
int length = postorder.length;
if(length == 0) {
return true;
}
return recur(postorder,0,length-1);
}
public boolean recur(int[] postorder,int i,int j) {
int p1 = i;
if(i>=j) {
return true;
}
while(postorder[i]<postorder[j]) {
i++;
}
int p2 = i;
while(postorder[i] > postorder[j]) {
i++;
}
int p3 = i;
if(p3 == j && recur(postorder,p1,p2-1) && recur(postorder,p2,p3-1)) {
return true;
}else {
return false;
}
}
public static void main(String args[]) {
Demo33 demo = new Demo33();
int[] postorder = {1,6,3,2,5};
System.out.println(demo.verifyPostorder(postorder));
}
}