7-4 是否同一棵二叉搜索树

在这里插入图片描述
在这里插入图片描述
方法还是固定的建树 然后用vector存放遍历的结果 利用vector可以直接判断是否相等的好处 判断遍历结果是否一样。

#include<vector>
#include<cstdio>
#include<stdlib.h>
using namespace std;
typedef struct node{
	struct node* left;
	struct node*right;
	int data;
}*bintree;
vector<int>bst1;
vector<int>bst2;
bintree insert(bintree bst,int x){
	if(!bst){
		bst = (bintree)malloc(sizeof(struct node));
		bst->data = x;
		bst->left = bst->right  =NULL;
	}else{
		if(bst->data<=x) bst->right = insert(bst->right,x);
		else if(bst->data>x) bst->left =insert(bst->left,x); 
	}
	return bst;
}
void preorder(bintree bst){
	if(bst){
		bst1.push_back(bst->data);
		preorder(bst->left);
		preorder(bst->right);
	}
}
void preorder1(bintree bst){
	if(bst){
		bst2.push_back(bst->data);
		preorder1(bst->left);
		preorder1(bst->right);
	}
}
int main()
{
	int n,l,x;
	scanf("%d",&n);
	while(n!=0){
		bintree bst = NULL;
		scanf("%d",&l);
		for(int i=0;i<n;i++){
			scanf("%d",&x);
			bst =insert(bst,x);
		}
		preorder(bst);
		for(int i=0;i<l;i++){
			bintree b=NULL;
			for(int j=0;j<n;j++){
				scanf("%d",&x);
				b = insert(b,x);
			}
			preorder1(b);
			if(bst1==bst2) printf("Yes\n");
			else printf("No\n");
			bst2.clear();
		}
		scanf("%d",&n);
		bst1.clear();
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值