博客
关于我
微软高频面试模拟题 剑指 Offer 33. 二叉搜索树的后序遍历序列
阅读量:232 次
发布时间:2019-03-01

本文共 972 字,大约阅读时间需要 3 分钟。

验证后序遍历序列是否为二叉搜索树

二叉搜索树的后序遍历序列验证方法

在二叉搜索树的后序遍历中,根节点总是最后一个访问的节点。通过这一特性,我们可以高效地验证给定的后序遍历序列是否构成二叉搜索树。

验证步骤如下

  • 找到序列的最后一个元素作为根节点

  • 确定根节点的左子节点和右子节点的范围

  • 根据二叉搜索树的性质,左子节点的值应小于根节点的值,右子节点的值应大于根节点的值

  • 递归地对左右子节点分别进行验证

  • 如何判断序列不是二叉搜索树

    如果在验证过程中发现某个节点的右子节点的值小于或等于根节点的值,或者左子节点的值大于或等于根节点的值,那么这个序列就不是二叉搜索树。

    代码实现

    class Solution {public:    bool verifyPostorder(vector
    & postorder) { return dfs(postorder, 0, postorder.size() - 1); } bool dfs(vector
    & postorder, int left, int right) { if (left >= right) return true; int val = postorder[right]; int k = left; while (k < right && postorder[k] <= val) { k++; } if (k == left) return false; int root = right; right = k - 1; if (root == -1) return true; return dfs(postorder, left, root) && dfs(postorder, root + 1, right); }}

    该代码使用递归的方式验证后序遍历序列是否为二叉搜索树。首先找到根节点,然后确定左子节点和右子节点的范围,最后递归验证左右子树是否满足二叉搜索树的性质。

    通过这种方法可以有效地判断给定的后序遍历序列是否构成二叉搜索树。

    转载地址:http://sjqv.baihongyu.com/

    你可能感兴趣的文章
    python | flanker,一个神奇的 Python 库!
    查看>>
    python | flower,一个强大的 Python 库!
    查看>>
    python | funcy,一个超强的 提供函数式编程工具 Python 库!
    查看>>
    python | ggplot,一个超强的 Python 库!
    查看>>
    python | grab,一个强大的 Python 库!
    查看>>
    python | h5py,一个无敌的关于 HDF5 的 Python 库!
    查看>>
    python | huey,一个非常厉害的 任务调度 Python 库!
    查看>>
    python | hypothesis,一个有趣的 Python 库!
    查看>>
    python | Indico,一个超酷的 Python 库!
    查看>>
    python | isort,一个有趣的 自动整理导入语句 的Python 库!
    查看>>
    python | jinja,一个超酷的 Python 库!
    查看>>
    python | joblib,一个强大的 Python 库!
    查看>>
    python | jsonschema,一个实用的 验证 JSON 数据结构 Python 库!
    查看>>
    python | lxml,一个超酷的 关于XML/HTML 文档 Python 库!
    查看>>
    python | mplfinance,一个有趣的金融数据可视化 Python 库!
    查看>>
    python | nipy,一个强大的关于 神经影像数据分析 的Python 库!
    查看>>
    python | NLTK,一个强大的 自然语言处理 Python 库!
    查看>>
    python | nupic,一个强大的 处理时间序列的Python 库!
    查看>>
    python | orange3,一个神奇的 Python 库!
    查看>>
    python | pdfminer,一个神奇的 关于PDF 文件的 Python 库!
    查看>>