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

在这里插入图片描述
这道题需要首先建立一个二叉搜索树,然后再一一对比。

#include<bits/stdc++.h>
#define fi first
#define se second
#define pb pusb_back
#define SZ(x) (ll)x.size()
#define rep(i,a,b) for(ll i=(a);i<=(b);++i)
#define per(i,a,b) for(ll i=(a);i>=(b);--i)
#define mem(a,b) memset(a,b,sizeof a)
using namespace std;
typedef long long ll;
typedef vector<ll> vi;
typedef pair<int,int> pii;
typedef struct Node *node;
template<class T>
inline void read(T &x) {
	x=0;
	ll f=0;
	char c=getchar();
	while(!isdigit(c)) {
		f|=(c=='-');
		c=getchar();
	}
	while(isdigit(c)) {
		x=(x<<3)+(x<<1)+c-'0';
		c=getchar();
	}
	if(f) x=-x;
}
const int maxn=1e2+5,inf=0x3f3f3f3f;
ll vis[maxn];
struct Node {//建立一个结构体存储节点的值和左右子树。
	ll val;
	node lf,rf;
};
node create(node t,ll x) {
	if(t==nullptr) {
		t=new Node({x,nullptr,nullptr});
	} else if(x<t->val)
		t->lf=create(t->lf,x);
	else
		t->rf=create(t->rf,x);
	return t;
}
bool check(node t,ll x) {
	if(!vis[t->val] && x!=t->val)
		return false;
	vis[t->val]=1;
	if(x==t->val)
		return true;
	if(x<t->val)
		return check(t->lf,x);
	else
		return check(t->rf,x);
}
int main() {
	ll n,m,x;
	while(cin >> n && n) {
		cin>>m;
		node t=nullptr;
		rep(i,1,n) {
			cin >> x;
			t=create(t,x);
		}
		while(m--) {
			ll f=1;
			mem(vis,0);
			rep(j,1,n) {
				cin >> x;
				if(!check(t,x))
					f=0;
			}
			if(f)
				puts("Yes");
			else
				puts("No");
		}
	}
	return 0;
}

建立二叉搜索树的模板:

node create(node t,ll x) {
	if(t==nullptr) {
		t=new Node({x,nullptr,nullptr});
	} else if(x<t->val)
		t->lf=create(t->lf,x);
	else
		t->rf=create(t->rf,x);
	return t;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值