7-37 是否同一棵二叉搜索樹 (25分)(極短代碼)

在這裏插入圖片描述
這道題如果你會建立二叉搜索樹的話應該就沒什麼問題了,比較的話就是從上到下依次比較看是否相等,比較簡單。代碼如下:

#include<bits/stdc++.h>
using namespace std;
const int maxn=1024+7;
int n,m,a[maxn],b[maxn];
void build1()
{
	memset(a,-1,sizeof a);
	for(int i=0;i<n;i++)
	{
		int id=1,x;
		cin>>x;
		while(1)
		{
			if(a[id]==-1)	{a[id]=x;break;}
			else if(x<a[id])	id*=2;
			else	id=2*id+1;
		}
	}
}
void build2()
{
	memset(b,-1,sizeof b);
	for(int i=0;i<n;i++)
	{
		int id=1,x;
		cin>>x;
		while(1)
		{
			if(b[id]==-1)	{b[id]=x;break;}
			else if(x<b[id])	id*=2;
			else	id=2*id+1;
		}
	}
}
bool check()
{
	for(int i=1;i<maxn;i++)
		if(a[i]!=b[i])	return false;
	return true;
}
int main()
{
	while(~scanf("%d %d",&n,&m)&&n>0)
	{
		build1();
		for(int i=0;i<m;i++)
		{
			build2();
			if(check())	puts("Yes");
			else	puts("No");
		}
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章