JZ23-二叉搜索树的后序遍历序列

二叉搜索树的后序遍历序列

https://www.nowcoder.com/practice/a861533d45854474ac791d90e447bafd?tpId=13&tags=&title=&diffculty=0&judgeStatus=0&rp=1&tab=answerKey

class Solution2 {
    public boolean VerifySquenceOfBST(int[] sequence) {
        if (sequence == null || sequence.length == 0)
            return false;
        return verify(sequence, 0, sequence.length - 1);
    }

    private boolean verify(int[] sequence, int first, int last) {
        if (last - first <= 1) {
            return true;
        }
        //找到根节点,并把数列分为左右子树
        int rootVal = sequence[last];
        int i = first;
        while (i < last && sequence[i] <= rootVal) {
            i++;
        }
        for (int j = i; j < last; j++) {//右子树中有小于根节点的话,就false
            if (sequence[j] < rootVal)
                return false;
        }
        return verify(sequence, first, i - 1) && verify(sequence, i, last - 1);//递归判断左右子树
    }
}

全部评论

相关推荐

头像
08-28 09:05
门头沟学院
投递美团等公司10个岗位
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务