【算法-java】判断该数组是不是某二叉搜索树的后序遍历的结果

来源:互联网 发布:阿里云客服是什么 编辑:程序博客网 时间:2024/05/22 13:12

输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。

public class Solution {    public boolean VerifySquenceOfBST(int [] sequence) {        if(sequence.length==0)return false;        return isSquenceOfBST(0,sequence.length-1,sequence);    }    public boolean isSquenceOfBST(int low,int high,int[] sequence){        /**        *检查当前是不是二叉搜索树的后序遍历的结果        **/        int root =sequence[high];        int mid =high-1;//左右子树分割线,左子树high下标        if(high<=low)return true;//递归终止条件        while(sequence[mid]>root){//定位mid            mid--;//从high往low定位            if(mid<low)return true;//符合二叉搜索树的后序遍历的结果        }                for(int i=low;i<=mid;i++){//检查是不是否存在不是二叉搜索树的后序遍历的结果            if(sequence[i]>root)return false;        }        /**        *递归检查是不是二叉搜索树的后序遍历的结果        **/        if(!isSquenceOfBST(low,mid,sequence)){//检查左子树            return false;        }        if(!isSquenceOfBST(mid+1,high-1,sequence)){//检查右子树            return false;        }        return true;    }}
阅读全文
0 0