前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >7-4 是否同一棵二叉搜索树 (25 分)

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

作者头像
Lokinli
发布2023-03-09 15:37:00
1600
发布2023-03-09 15:37:00
举报
文章被收录于专栏:以终为始

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

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

输入格式:

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

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

输出格式:

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

输入样例:

代码语言:javascript
复制
4 2
3 1 4 2
3 4 1 2
3 2 4 1
2 1
2 1
1 2
0

输出样例:

代码语言:javascript
复制
Yes
No
No
代码语言:javascript
复制
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 100006;
struct node {
    int data;
    struct node *lc, *rc;
};
struct node *creat(struct node *root, int x )
{
    if(root == NULL) {
        root = new node;
        root -> data = x;
        root -> lc = NULL;
        root -> rc = NULL;
    }
    else {
        if(x > root -> data)
        {
            root -> rc = creat(root -> rc, x);
        }
        else {
            root -> lc = creat(root -> lc, x);
        }
    }
    return root;
};

bool ok(struct node *t1, struct node *t2)
{
    if(t1 == NULL && t2 == NULL) return 1;
    else if(t1 -> data != t2 -> data)
    {
        return 0;
    }
    else if(ok(t1->lc,t2->lc) && ok(t1->rc,t2 -> rc)) return 1;
    else return 0;
}
int a[55], b[55];
int main()
{
    ios::sync_with_stdio(0);
    int n,l;
    while(cin >> n)
    {
        if(n == 0) return 0;
        cin >> l;
        for(int i = 0; i < n; i ++) cin >> a[i];
        struct node *t1, *t2;
        t1 = NULL; t2 = NULL;
        for(int i = 0; i < n; i ++)
        {
            t1 = creat(t1,a[i]);
        }
        while(l --)
        {
            t2 = NULL;
            for(int i = 0; i < n; i ++) cin >> b[i];
            for(int i = 0; i < n; i ++) t2 = creat(t2,b[i]);
            bool f = ok(t1,t2);
            if(f) cout << "Yes" << endl;
            else cout << "No" << endl;
        }
    }

    return 0;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2019-03-11,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 输入格式:
  • 输出格式:
  • 输入样例:
  • 输出样例:
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档