1. 程式人生 > >劍指offer——(24)二叉搜尋樹的後序遍歷序列

劍指offer——(24)二叉搜尋樹的後序遍歷序列

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;
    }

}