7-20 Binary Search Tree

题目

题意:给定含有n个元素的序列可建出相应的二叉搜索树, 以及给出m个查询序列,问这些待查询序列的二叉搜索树是否和最初的二叉搜索树相同。测试样例以0结束

tip:建树+遍历对比

#include<iostream>
using namespace std;
struct node {
	int val;
	struct node *l,*r;
};
struct node* create(struct node* root,int val) {
	if(root==NULL) {
		root=new node();
		root->val=val;
		root->l=root->r=NULL;
	} else if(root->val>=val)
		root->l=create(root->l,val);
	else root->r=create(root->r,val);
	return root;
}
bool checked(struct node* root,struct node* temp) {
	if(root==NULL&&temp==NULL)
		return true;
	else if(root->val==temp->val)
		return checked(root->l,temp->l)&&checked(root->r,temp->r);
	else return false;
}
int main() {
	int n,m;
	cin>>n;
	while(n) {
		cin>>m;
		struct node* root=NULL;
		for(int i=0; i<n; ++i) {
			int t;
			cin>>t;
			root=create(root,t);
		}
		for(int i=0; i<m; ++i) {
			struct node* temp=NULL;
			for(int j=0; j<n; ++j) {
				int t;
				cin>>t;
				temp=create(temp,t);
			}
			if(checked(root,temp))
				cout<<"Yes\n";
			else cout<<"No\n";
		}
		cin>>n;
	}
	return 0;
}
发布了382 篇原创文章 · 获赞 17 · 访问量 1万+

猜你喜欢

转载自blog.csdn.net/qq_40991687/article/details/104268387