题目
输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
思路
1.使用递归:因为是二叉搜索树的话 左子树的所有节点小于root 并且root小于所有右子树节点 这样的话 root是后序遍历的最后一位,根据root的val判断左右子树序列 然后在递归左右子树序列
2.二叉搜索树的中序遍历是递增的 如果将中序遍历当做stack的push序列,那么其后序遍历就是其中的一个pop序列
代码
1.递归
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
//1.边界值的判断 2.根据二叉搜索树的性质 找到root 找到左右子序列 递归
if(sequence==null||sequence.length==0){
return false;
}
return verify(sequence,0,sequence.length-1);
}
public static boolean verify(int[] sequence,int begin,int end){
//若遍历完了还没报错就证明是该二叉搜索树的后序遍历,则返回false
if(begin>=end){
return true;
}
//get rootVal
int root = sequence[end];
int curIndex = begin;
while(curIndex<end&&sequence[curIndex]<=root){
curIndex++;
}
//过滤不是后序遍历的序列
for(int i=curIndex;i<end;i++){
if(sequence[i]<root){
return false;
}
}
//第end位是root
return verify(sequence,begin,curIndex-1)&&verify(sequence,curIndex,end-1);
}
}
2.栈的性质
import java.util.*;
public class Solution {
public boolean VerifySquenceOfBST(int [] sequence) {
/*//1.边界值的判断 2.根据二叉搜索树的性质 找到root 找到左右子序列 递归
if(sequence==null||sequence.length==0){
return false;
}
return verify(sequence,0,sequence.length-1);
}
public static boolean verify(int[] sequence,int begin,int end){
//若遍历完了还没报错就证明是该二叉搜索树的后序遍历,则返回false
if(begin>=end){
return true;
}
//get rootVal
int root = sequence[end];
int curIndex = begin;
while(curIndex<end&&sequence[curIndex]<=root){
curIndex++;
}
//过滤不是后序遍历的序列
for(int i=curIndex;i<end;i++){
if(sequence[i]<root){
return false;
}
}
//第end位是root
return verify(sequence,begin,curIndex-1)&&verify(sequence,curIndex,end-1);
*/
int len = sequence.length;
if(sequence==null || len==0){
return false;
}
int[] post = new int[len];
for(int i=0;i<len;i++){
post[i]=sequence[i];
}
Arrays.sort(sequence);
return isPopOrder(sequence,post);
}
public static boolean isPopOrder(int[] in,int[] post){
if(in.length==0|| post.length==0){
return false;
}
Stack<Integer> s = new Stack<Integer>();
int index = 0;
for(int i =0;i<in.length;i++){
s.push(in[i]);
while(!s.empty()&&post[index]==s.peek()){
s.pop();
index++;
}
}
return s.isEmpty();
}
}