问题说明:
1.二叉搜索树又名二叉排序树,即左孩子小于根结点,右孩子大于根结点;
2.给定一个整数数组序列,判定该序列是否为某个二叉搜索树的后序序列;
3.假设输入的数组任意两个数字各不相同。
// judge post sequence is some binarySearchTree post travel squence
public static boolean isPostSequenceOfBST(int[] post){
int len = 0;
if(null == post ||(len = post.length) == 0){
throw new IllegalArgumentException();
}
return isPostSequenceOfBST(post, 0, len - 1);
}
private static boolean isPostSequenceOfBST(int[] post, int postBegin, int postEnd){
// postBegin > postEnd
if(postBegin > postEnd){
return false;
}
// postBegin == postEnd
boolean isSingleTree = (postBegin == postEnd);
if(isSingleTree){
return true;
}
// postBegin < postEnd
int rootValue = post[postEnd];
// equal to rightBeginIndex first index of more than rootValue
// at most equal to postEnd
int firstMoreThanIndex = postBegin;
while(firstMoreThanIndex < postEnd && post[firstMoreThanIndex] < rootValue){
firstMoreThanIndex ++;
}
int rightExclusiveEndIndex = firstMoreThanIndex + 1;
while(rightExclusiveEndIndex < postEnd){
if(post[rightExclusiveEndIndex] < rootValue){
return false;
}
rightExclusiveEndIndex ++;
}
// rightExclusiveEnd == postEnd
int leftTreeLen = firstMoreThanIndex - postBegin;
int rightTreeLen = rightExclusiveEndIndex - firstMoreThanIndex;
boolean isLeftTreeOrNull =(leftTreeLen != 0 ? isPostSequenceOfBST(post, postBegin, firstMoreThanIndex - 1) : true);
boolean isRightTreeOrNull =(rightTreeLen != 0 ? isPostSequenceOfBST(post, firstMoreThanIndex, rightExclusiveEndIndex - 1) : true);
return (isLeftTreeOrNull && isRightTreeOrNull);
}