面试题:判断整数序列是不是二元查找树的后序遍历结果

文章介绍了一种方法来判断给定的整数数组是否符合二元查找树的后序遍历特性。通过分析后序遍历的规律(最后一个元素为根节点,左边小于根节点,右边大于根节点),将序列分成左右两部分并递归地进行验证。代码示例展示了如何实现这一过程。
摘要由CSDN通过智能技术生成

题目:输入一个整数数组,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。 例如输入5、7、6、9、11、10、8,由于这一整数序列是如下树的后序遍历结果:
8
/ \
6 10
/ \ / \
5 7 9 11
因此返回true。
如果输入7、4、6、5,没有哪棵树的后序遍历的结果是这个序列,因此返回false。
分析:这是一道trilogy的笔试题,主要考查对二元查找树的理解。
在后续遍历得到的序列中,最后一个元素为树的根结点。从头开始扫描这个序列,比根结点小的元素都应该位于序列的左半部分;从第一个大于跟结点开始到跟结点前面的一个元素为止,所有元素都应该大于跟结点,因为这部分元素对应的是树的右子树。根据这样的划分,把序列划分为左右两部分,我们递归地确认序列的左、右两部分是不是都是二元查找树。

using namespace std;    
///    
// Verify whether a squence of integers are the post order traversal    
// of a binary search tree (BST)    
// Input: squence - the squence of integers    
//          length    - the length of squence    
// Return: return ture if the squence is traversal result of a BST,    
//           otherwise, return false    
///    
bool verifySquenceOfBST(int squence[], int length)    
{    
      if(squence == NULL || length <= 0)    
            return false;    
      // root of a BST is at the end of post order traversal squence    
      int root = squence[length - 1];    
      // the nodes in left sub-tree are less than the root    
      int i = 0;    
      for(; i < length - 1; ++ i)    
        {    
            if(squence[i] > root)    
                  break;    
        }    
   
      // the nodes in the right sub-tree are greater than the root    
      int j = i;    
      for(; j < length - 1; ++ j)    
        {    
            if(squence[j] < root)    
                  return false;    
        }    
   
      // verify whether the left sub-tree is a BST    
      bool left = true;    
      if(i > 0)    
              left = verifySquenceOfBST(squence, i);    
   
      // verify whether the right sub-tree is a BST    
      bool right = true;    
      if(i < length - 1)    
              right = verifySquenceOfBST(squence + i, length - i - 1);    
   
      return (left && right);   

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

EthanMilk

你的鼓励是我创作的最大动力谢谢

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值