二叉搜索树的后序遍历序列
二叉搜索树的后序遍历序列
https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&&tqId=11176&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking
二叉树的后续遍历:先访问左节点,再访问右节点,最后访问根节点
所以一个后续遍历的数组,最后一位肯定是二叉树的根节点
何为二叉搜索树:左节点必定小于根节点,右节点必定小于根节点;左子树和右子树也是二叉搜索树
所以思路就来了:
我们可以直接拿到二叉树的根节点,然后找到其左子树的所有节点和右子树的所有节点,
然后切成两个二叉树,继续递归调用去做同样的判断
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);
}
剑指offer 文章被收录于专栏
为刷过的每一道题都书写一篇题解,便于重复练习~
SHEIN希音公司福利 254人发布

