题意:
给出二叉排序树的插入序列,判断给出的这些序列跟第一个序列是否是同一棵树。
重点:
学会创建二叉搜索树
学会判断两棵树是否是相同的两棵树
#include <iostream>
#include <vector>
#include <string>
#include <cmath>
#include <algorithm>
#include <queue>
#include <cstdio>
#include <cctype>
#include <unordered_map>
#include <map>
#include <cstring>
using namespace std;
const int N = 30;
struct tree{
int val;
tree* left, *right;
tree(int x){
val = x;
left = right = nullptr;
}
};
void create(tree* &root, int val){
if(!root){
root = new tree(val);
}else if(val > root->val)
create(root->right, val);
else
create(root->left, val);
}
bool same(tree* p, tree* q){
if(!p || !q) return p==q;
if(p->val != q->val) return false;
return same(p->left, q->left)&&same(p->right, q->right);
}
int main(){
int m, n, x;
while(cin>>m){
if(m==0) break;
cin>>n;
tree* root = nullptr;
for(int i = 0; i < m; i++){
cin>>x;
create(root, x);
}
while(n--){
int tag = 0;
tree* newrt = nullptr;
for(int i = 0; i < m; i++){
cin>>x;
create(newrt, x);
}
if(same(root, newrt)) cout<<"Yes"<<endl;
else cout<<"No"<<endl;
}
}
return 0;
}