二叉排序树(BST)的判定

【问题描述】课后第6题。试写一个判别给定二叉树是否为二叉排序树的算法。以前序遍历序列和中序遍历序列给出该二叉树的结点,并创建该二叉树。然后再进行判断。请注意,树中结点关键字可能相同。

【样例输入1】

6 4 5 8 6 9 0

4 5 6 6 8 9 0
【样例输出1】

true

【样例输入2】

6 4 7 8 0

4 7 6 8 0
【样例输出2】

false

【提示】若直接根据给定的中序是否有序来进行判断,此种判断方法不得分。务必先创建二叉树的链式存储,再对其进行判断。

#include<iostream>
using namespace std;
#include<cstdlib>
int i=0;
int ret[50];
typedef struct Node
{
    int key;
    struct Node*LChild,*RChild;
}BSTNode,*BSTree;
BSTree build(int pre[],int in[],int length)
{
    if(length==0)
        return NULL;
    int i,leftlength,rightlength;
    int root;
    BSTree T;
    root=pre[0];
    for(i=0;i<length;i++)
    {
        if(in[i]==root)
            break;
    }
    leftlength=i;
    rightlength=length-i-1;
    T=(BSTree)malloc(sizeof(BSTree));
    T->key=root;
    T->LChild=NULL;
    T->RChild=NULL;
    T->LChild=build(&pre[1],&in[0],leftlength);
    T->RChild=build(&pre[i+1],&in[i+1],rightlength);
    return T;
}

void InOrder(BSTree bt, int ret[], int &i)
{
    if(bt==NULL)
        return;
    else
    {
        InOrder(bt->LChild, ret, i);
        ret[i]=bt->key;
        i++;
        InOrder(bt->RChild, ret, i);
    }
}

bool judge(BSTree bt)
{
    int ret[50];
    int i = 0;
    InOrder(bt, ret, i);
    for(int j=1; j<i; j++)
    {
        if(ret[j]<ret[j-1])
            return false;
    }
    return true;
}

int main()
{
    int arr1[50],arr2[50];
    int i=0,j=0,cot=0,n;
    BSTree bt;
    bt=(BSTree)malloc(sizeof(BSTNode));
    while(cin>>n&&n!=0)
    {
        arr1[i]=n;
        i++;
        cot++;
    }
    while(cin>>n&&n!=0)
    {
        arr2[j]=n;
        j++;
    };
    bt=build(arr1,arr2,cot);
    if(judge(bt))
        cout<<"true";
    else
        cout<<"false";
    return 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值