剑指offer——(24)二叉搜索树的后序遍历序列

版权声明:本文自由转载,转载请注明出处。 https://blog.csdn.net/qq_38071429/article/details/85002091

public class Solution {
    public boolean VerifySquenceOfBST(int [] sequence) {
    	if(sequence.length==0) return false;
    	if(sequence.length==1) return true;
    	
    	return isLastOrder(0, sequence.length-1, sequence);
     	
    }
    
    boolean isLastOrder(int start, int end, int arr[]) {
    	// root为根节点
        int root = arr[end]; 
    	int i = 0;
        // 找到当前序列的左右序列分界
    	for(;i < end; i++) {
    		if(arr[i] > root) {
    			break;
    		}
    	}
    	
    	int j = i;
    	// 因为是判断是否为二叉搜索树的后序遍历 所以如果右序遍历中存在比根节点小的值 即刻返回false
    	for(; j < end;j++) {
    		if(root > arr[j]) {
    			//System.out.println(root +":"+ arr[j]);
    			return false;
    		}
    	}
    	// 否则即可能组成某棵二叉搜索树的后序遍历 继续递归遍历左右序列
    	if(i - 1 >= 0) isLastOrder(0, i - 1, arr);
    	if(j - 1 - i >= 0) isLastOrder(i, j - 1, arr);   	
    	// 所有序列值全部符合定义的话返回true
    	return true;
    }

}   

猜你喜欢

转载自blog.csdn.net/qq_38071429/article/details/85002091