AcWing 46. 二叉搜索树的后序遍历序列
原题链接
简单
作者:
STU756
,
2020-09-01 13:22:40
,
所有人可见
,
阅读 394
public boolean verifySequenceOfBST(int [] sequence) {
if(sequence == null || sequence.length < 2) return true;
return verifySequenceOfBST(sequence, 0, sequence.length - 1);
}
private boolean verifySequenceOfBST(int[] sequence, int st, int ed) {
if(ed - st <= 1) return true;
int rootVal = sequence[ed];
int curIndex = st;
while(curIndex < ed && sequence[curIndex] <= rootVal) ++curIndex; //左子树都小于等于rootVal
for(int i = curIndex; i < ed; i++) { //判断右子树大于等于rootVal
if(sequence[i] < rootVal) { //不符合条件返回false
return false;
}
}
//drill down
return verifySequenceOfBST(sequence, st, curIndex-1) && verifySequenceOfBST(sequence, curIndex, ed - 1);
}