当前位置:网站首页>是否同一棵二叉搜索树 (25 分)
是否同一棵二叉搜索树 (25 分)
2022-04-23 08:35:00 【怀化第二深情】
给定一个插入序列就可以唯一确定一棵二叉搜索树。然而,一棵给定的二叉搜索树却可以由多种不同的插入序列得到。例如分别按照序列{2, 1, 3}和{2, 3, 1}插入初始为空的二叉搜索树,都得到一样的结果。于是对于输入的各种插入序列,你需要判断它们是否能生成一样的二叉搜索树。
输入格式:
输入包含若干组测试数据。每组数据的第1行给出两个正整数N (≤10)和L,分别是每个序列插入元素的个数和需要检查的序列个数。第2行给出N个以空格分隔的正整数,作为初始插入序列。随后L行,每行给出N个插入的元素,属于L个需要检查的序列。
简单起见,我们保证每个插入序列都是1到N的一个排列。当读到N为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<bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
};
typedef Node* Tree;
Tree insert(Tree BT, int x) {
if (!BT) {
BT = new (Node);
BT->data = x;
BT->left = BT->right = NULL;
} else if (x < BT->data)
BT->left = insert(BT->left, x);
else if (x > BT->data)
BT->right = insert(BT->right, x);
return BT;
}
bool judge(Tree a, Tree b) {
if (a == NULL && b == NULL)
return true;
else if ((a != NULL && b == NULL) || (a == NULL && b != NULL))
return false;
else if (a->data == b->data)
return judge(a->left,b->left)&&judge(a->right,b->right);
return false;
}
int main(){
int n,l,k;
while(cin>>n&&n){
cin>>l;
Tree BT=NULL;
int x;
for(int i=0;i<n;i++){
cin>>x;
BT=insert(BT,x);
}
for(int i=0;i<l;i++){
Tree Temp=NULL;
for(int j=0;j<n;j++){
cin>>x;
Temp=insert(Temp,x);
}
if(judge(Temp,BT))cout<<"Yes\n";
else cout<<"No\n";
}
}
}
版权声明
本文为[怀化第二深情]所创,转载请带上原文链接,感谢
https://blog.csdn.net/dege2929512534/article/details/124339281
边栏推荐
猜你喜欢
![[C语言] 文件操作《一》](/img/89/b19dda13d27e37fedf6736c102245b.png)
[C语言] 文件操作《一》

Notes on 30 steps of introduction to the Internet of things of yangtao electronics STM32 III. cubemx graphical programming and setting the IO port on the development board

Idea is configured to connect to the remote database mysql, or Navicat fails to connect to the remote database (solved)

RCC introduction of Hal Library

PgSQL wants to implement all kinds of column sub query operations of MySQL

Yangtao electronic STM32 Internet of things entry 30 step notes II. Cube ide download, installation, sinicization and setting

bashdb下载安装

2022-04-22 OpenEBS云原生存储

DJ音乐管理软件Pioneer DJ rekordbox

cadence的工艺角仿真、蒙特卡洛仿真、PSRR
随机推荐
idea配置连接远程数据库MySQL,或者是Navicat连接远程数据库失败问题(已解决)
K210学习笔记(二) K210与STM32进行串口通信
Overview of bus structure
synchronized 锁的基本用法
How to encrypt devices under the interconnection of all things
ELK生产实践
对OutputStream类的flush()方法的误解
虚拟线上展会-线上vr展馆实现24h沉浸式看展
Type anonyme (Principes fondamentaux du Guide c)
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
DOM learning - add + - button
面了一圈,整理了这套面试题。。
jsp页面编码
增强现实技术是什么?能用在哪些地方?
MySQL查询两张表属性值非重复的数据
IDEA导入commons-logging-1.2.jar包
Yangtao electronic STM32 Internet of things introduction 30 steps notes 1. The difference between Hal library and standard library
请提前布局 Star Trek突破链游全新玩法,市场热度持续高涨
2022-04-22 OpenEBS云原生存储
【IndexOf】【lastIndexOf】【split】【substring】用法详解