当前位置:网站首页>是否同一棵二叉搜索树 (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
边栏推荐
- RPC procedure
- 关于数组复制问题
- 项目上传部分
- 耳穴诊疗随笔0421
- 'bully' Oracle enlarged its move again, and major enterprises deleted JDK overnight...
- vmware 搭建ES8的常见错误
- 洋桃电子STM32物联网入门30步笔记四、工程编译和下载
- 应纳税所得额
- Yangtao electronic STM32 Internet of things entry 30 step notes IV. engineering compilation and download
- uni-app和微信小程序中的getCurrentPages()
猜你喜欢
洋桃电子STM32物联网入门30步笔记三、新建CubeIDE工程和设置讲解
QT compilation qtxlsx Library
增强现实技术是什么?能用在哪些地方?
Failed to convert a NumPy array to a Tensor(Unsupported Object type int)
Overview of bus structure
汇编语言与逆向工程 栈溢出漏洞逆向分析实验报告
引用传递1
Yangtao electronic STM32 Internet of things entry 30 step notes II. Cube ide download, installation, sinicization and setting
Flash project cross domain interception and DBM database learning [Baotou cultural and creative website development]
STM32 uses Hal library. The overall structure and function principle are introduced
随机推荐
Use of Arthas in JVM tools
idea打包 jar文件
Copy array in JS
第一性原理 思维导图
Star Trek强势来袭 开启元宇宙虚拟与现实的梦幻联动
What is RPC
Reference passing 1
An example of network communication based on TCP / IP protocol -- file transmission
pdf加水印
synchronized 锁的基本用法
pgsql想实现mysql一样样的列子查询操作
汇编语言与逆向工程 栈溢出漏洞逆向分析实验报告
信息收集相关知识点及题解
让地球少些“碳”息 度能在路上
洋桃电子STM32物联网入门30步笔记二、CubeIDE下载、安装、汉化、设置
rust 使用tokio的Notify 和timeout实现类似可超时条件变量的效果
LeetCode396.旋转数组
Asan minimalism
Qtablewidget header customization and beautification developed by pyqt5 (with source code download)
洋桃電子STM32物聯網入門30步筆記一、HAL庫和標准庫的區別