二叉树的后续遍历:先访问左节点,再访问右节点,最后访问根节点
所以一个后续遍历的数组,最后一位肯定是二叉树的根节点
何为二叉搜索树:左节点必定小于根节点,右节点必定小于根节点;左子树和右子树也是二叉搜索树
所以思路就来了:
我们可以直接拿到二叉树的根节点,然后找到其左子树的所有节点和右子树的所有节点,
然后切成两个二叉树,继续递归调用去做同样的判断
public boolean VerifySquenceOfBST(int [] sequence) {
if(sequence == null || sequence.length == 0)
return false;
return toCut(sequence,0,sequence.length-1);
}
public boolean toCut(int[] arr,int first,int last){
if(last-first <= 1){
return true;
}
int rootVal = arr[last];
int cutIndex = first;
while(cutIndex < last && arr[cutIndex] <= rootVal)
cutIndex++;
for(int i = cutIndex; i < last; i++){
if(arr[i] < rootVal)
return false;
}
return toCut(arr,first,cutIndex-1) && toCut(arr,cutIndex,last-1);
}

京公网安备 11010502036488号