PTA习题 5-4 是否同一棵二叉搜索树(二叉搜索树的构建以及相同树的判断)

5-4 是否同一棵二叉搜索树   (25分)

给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。

输入格式:

输入包含若干组测试数据。每组数据的第1行给出两个正整数NN (\le 1010)和LL,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出NN个以空格分隔的正整数,作为初始插入序列。最后LL行,每行给出NN个插入的元素,属于LL个需要检查的序列。

简单起见,我们保证每个插入序列都是1到NN的一个排列。当读到NN为0时,标志输入结束,这组数据不要处理。

输出格式:

对每一组需要检查的序列,如果其生成的二叉搜索树跟对应的初始序列生成的一样,输出“Yes”,否则输出“No”。

输入样例:

4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

输出样例:

Yes
No
No

#include <iostream>
#include <cstdio>
#include <cmath>
#include <queue>
#include <stack>
#include <map>
#include <algorithm>
#include <vector>
#include <string>
#include <cstring>
#include <sstream>
#define INF 100000000

using namespace std;

int n,l;
int a[100];
struct Btree
{
    int x;
    Btree *left;
    Btree *right;
    Btree()
    {
        left=NULL;
        right=NULL;
    }
};
typedef struct Btree Btree;
Btree *root;

Btree* Build(int *x)
{
    Btree *r=new Btree;
    r->x=x[0];
    r->left=NULL;
    r->right=NULL;
    for(int i=1;i<n;i++)
    {
        int xx=x[i];
        Btree *p=r,*q=NULL;
        while(p)
        {
            q=p;
            if(xx<p->x)
            {
                p=p->left;
            }
            else
            {
                p=p->right;
            }
        }
        p=new Btree;
        p->x=xx;
        if(xx<q->x)
        {
            q->left=p;
        }
        else
        {
            q->right=p;
        }
    }
    return r;
}

int c[100];

int judge(Btree *p,Btree *q)
{
    if(p==NULL && q==NULL) return 1;
    if(p==NULL && q!=NULL || p!=NULL &&q==NULL) return 0;
    if(p->x!=q->x) return 0;
    return judge(p->left,q->left)*judge(p->right,q->right);
}




int main()
{
    while(scanf("%d",&n)==1)
    {
        if(n==0) return 0;
        scanf("%d",&l);
        for(int i=0;i<n;i++)
        {
            scanf("%d",&a[i]);
        }
        root=Build(a);
        while(l--)
        {
            for(int i=0;i<n;i++)
            {
                scanf("%d",&c[i]);
            }
            Btree *tmp=Build(c);
            int ans=judge(tmp,root);
            if(ans==1)
            {
                printf("Yes\n");
            }
            else
            {
                printf("No\n");
            }
        }
    }
    return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值