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

题目:输入一个整数数列,判断该数组是不是某二元查找树的后序遍历的结果。如果是返回true,否则返回false。

 

解法:用递归的方法解决。数组最后一个元素肯定是根节点的值,找出左子树(数组左侧所有比根节点小的值)和右子树(数组右侧,除根节点外,所有比根节点大的值),注意不能出现左子树中有元素比根节点大、右子树中有元素比根节点小,然后递归查看左子树和右子树是否为后序遍历的结果。

 

C++代码如下:

#include<iostream>
using namespace std;

//check whether array arr with length len is the postorder of certain binary search tree
bool is_postorder_traversal(int* arr,int len)
{
    int mid;  //mid used to index the first element on the right subtree of the root
    if(arr==NULL||len==0)
        return false;
    if(len<=2)
        return true;
    int i;
    for(i=0;i<len-1;i++)
    {
        if(arr[i]>arr[len-1])   //all the elements on the left subtree of the root is smaller the the root
            break;
    }
    mid=i;
    for(;i<len-1;i++)
    {
        if(arr[i]<arr[len-1]) //it is error that some element on the right subtree is smaller than the root
            return false;
    }
    if(mid==0)   //all the elements except the root is on th right subtree of the root
        return is_postorder_traversal(arr,len-1);
    if(mid==len-1)   //all the elements except the root is on th left subtree of the root
        return is_postorder_traversal(arr,mid);
    return is_postorder_traversal(arr,mid)&&is_postorder_traversal(arr+mid,len-mid-1);
}

int main()
{
    int a[]={5,7,6,9,11,10,8};
    cout<<is_postorder_traversal(a,7)<<endl;
    int b[]={7,4,6,9};
    cout<<is_postorder_traversal(b,4)<<endl;
    int c[]={1,2,3,4,5,6,7,8,9};
    cout<<is_postorder_traversal(c,9)<<endl;
    int d[]={9,8,7,6,5,4,3,2,1};
    cout<<is_postorder_traversal(d,9)<<endl;
    return 0;
}


 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值