剑指offer-二叉搜索树的后序遍历序列C++实现

剑指offer-二叉搜索树的后序遍历序列C++实现

原题链接
在这里插入图片描述

#include <iostream>
#include <vector>

using namespace std;

class Solution {
public:
    bool VerifySquenceOfBST(vector<int> sequence) {
        // 树的总节点数量
        int size = sequence.size();
        // 由题意可得,空树不是二叉搜索树
        if (size == 0)return false;
        // 递归判断二叉搜索树
        return check_behind_iter(sequence, 0, size - 1);
    }

    // 构建辅助函数 left 左边界 right 右边界
    bool check_behind_iter(vector<int> sequence, int left, int right) {
        // 子树只有一个节点时(叶子节点),返回true
        if (left > right)return true;
        // 根节点的值
        int root = sequence[right];
        // 划分右子树区间
        int r_tree = right - 1;
        while (r_tree >= 0 && sequence[r_tree] > root)r_tree--;
        // 检查左子树区间的值是否都小于根节点的值,此时r_tree指向左子树右边界
        for (int i = left; i <= r_tree; i++) {
            if (sequence[i] > root) return false;
        }
        // 分别检查左子树和右子树
        return check_behind_iter(sequence, left, r_tree)
               && check_behind_iter(sequence, r_tree + 1, right - 1);
    }
};

思路:
二叉搜索树的定义是左子树的值都小于根节点的值,右子树的值都大于根节点的值。后序遍历序列中右边界即使根节点,因为后序遍历顺序为左右根,故知道了根节点在序列中的位置后,可以逆序推出右子树和左子树的范围,最后分别检查左右子树范围是否符合二叉搜索树即可。
时间复杂度O(N^2),空间复杂度O(N)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值