您的位置:首页 > Web前端

剑指offer刷题之java实现的二叉搜索树的后序遍历序列

2015-08-09 19:19 676 查看
package mine;
/**
 * 
 * @author		毛二
 * @data   		2015-8-9
 * @comments	二叉搜索树的后序遍历序列
 * 输入一个整数数组,判断该数组是不是某二叉搜索树的后序遍历的结果。
 * 如果是则输出Yes,否则输出No。假设输入的数组的任意两个数字都互不相同。
 */
public class PostSeqOfTwoSearchTree {
    public static boolean VerifySquenceOfBST(int [] sequence) {
        //边界值判断时,不光要判断数组是否为null,还有可能长度为零。
    	if(sequence == null || sequence.length == 0)
        	return false;
    	return oneVerifySquenceOfBST(sequence,0,sequence.length-1);
    }
    
    public static boolean oneVerifySquenceOfBST(int[] a,int low,int high){
    	boolean f = true;
        int l = low,h = high-1;
        System.out.println("start: "+"l = "+l+"  h = "+h);
        if(low <high){
        	while(l<h && a[l]<a[high])
        		l++;
        	while(l<h && a[h]>a[high])
        		h--;
        	System.out.println("l = "+l+"  h = "+h);
        	
	        if(l==h){
	    		return oneVerifySquenceOfBST(a,low,l-1)&&oneVerifySquenceOfBST(a,l,high-1);
	    	}
	        else {
	        	f = false;
	        }
	    }
        return f;
    }
    public static void main(String[] args) {
		int[] a ={};//= null;
			//{7,4,6,5};
		//{5,7,6,9,11,10,8};
		System.out.println(VerifySquenceOfBST(a));
	}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: