博客
关于我
微软高频面试模拟题 剑指 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/

    你可能感兴趣的文章
    sqlserver学习笔记(三)—— 为数据库添加新的用户
    查看>>
    org.apache.ibatis.exceptions.PersistenceException:
    查看>>
    org.apache.ibatis.exceptions.TooManyResultsException: Expected one result (or null) to be returned
    查看>>
    org.apache.ibatis.type.TypeException: Could not resolve type alias 'xxxx'异常
    查看>>
    org.apache.poi.hssf.util.Region
    查看>>
    org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    查看>>
    org.apache.zookeeper.KeeperException$ConnectionLossException: KeeperErrorCode = ConnectionLoss for /
    查看>>
    org.hibernate.HibernateException: Unable to get the default Bean Validation factory
    查看>>
    org.hibernate.ObjectNotFoundException: No row with the given identifier exists:
    查看>>
    SQL-CLR 类型映射 (LINQ to SQL)
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.orm.hibernate3.support.OpenSessionInViewFilter
    查看>>
    org.springframework.web.multipart.MaxUploadSizeExceededException: Maximum upload size exceeded
    查看>>
    org.tinygroup.serviceprocessor-服务处理器
    查看>>
    org/eclipse/jetty/server/Connector : Unsupported major.minor version 52.0
    查看>>
    org/hibernate/validator/internal/engine
    查看>>
    Orleans框架------基于Actor模型生成分布式Id
    查看>>
    SQL-36 创建一个actor_name表,将actor表中的所有first_name以及last_name导入改表。
    查看>>
    ORM sqlachemy学习
    查看>>
    Ormlite数据库
    查看>>