[Niuke.com] 24. Post-order traversal sequence of binary search tree

Input an integer array to determine whether the array is the result of a post-order traversal of a binary search tree. If yes, output Yes, otherwise output No. Assume that any two numbers in the input array are different from each other

package leetcode;

public class L23SequenceOFBST {
	public boolean VerifySquenceOfBST(int[] sequence) {
		if(sequence==null)return false;
		int len = sequence.length;
		if(len<=0)return false;
		if(len==1)return true;
		return VerifySquenceOfBSTCore(sequence, 0,len-1);
	}

	private boolean VerifySquenceOfBSTCore(int[] sequence,int start, int len) {
		int root=sequence[len];
		int i;
		for(i=start;i<len;i++){
			if(sequence[i]>root)
				break;
		}
		int j;
		for(j=i;j<len;j++){
			if(sequence[j]<root)
				return false;
		}
		boolean left=true;
		if(i>start){
			left=VerifySquenceOfBSTCore(sequence,start,i-1);
		}
		boolean right=true;
		if(len-i>1){
			right=VerifySquenceOfBSTCore(sequence,i,len-1);
		}
		return left&&right;
	}
	public static void main(String[] args) {
		int[] seq={7,4,6,5};
		L23SequenceOFBST l23= new L23SequenceOFBST();
		System.out.println(l23.VerifySquenceOfBST(seq));
		int [] seq2={5,7,6,9,11,10,8};
		System.out.println(l23.VerifySquenceOfBST(seq2));
	}
}

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326386502&siteId=291194637