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

解题思路:首先保存输入的第一组数据,该组数据与其他组信息比较,在输入数据时保存数据的根结点,根据根结点构造树,递归比较两棵树的元素大小。

#include<iostream>
using  namespace std;
typedef struct Tree {
	int data;
	 Tree *left;
	 Tree *right;
}search,*search_tree;
void InsertNode(search_tree root, search_tree newNode) {//插入新的结点
	while (root != NULL) {
		if (newNode->data > root->data) {
			if(root->right!=NULL)
			root = root->right;
			else {
				root->right = newNode;
				return;
			}
		}
		else {
			if(root->left!=NULL)
			root = root->left;
			else {
				root->left = newNode;
				return;
			}
		}
	}
}
int compareTree(search_tree Node1, search_tree Node2) {//输入根结点比较两课树各个元素的大小
	if ((Node1 == NULL&&Node2 != NULL) || (Node1 != NULL&&Node2 == NULL)) {
		return 0;
	}else if (Node1 != NULL&&Node2 != NULL) {
		if (Node1->data == Node2->data) {
			if (!compareTree(Node1->left, Node2->left)) {
				return false;
			}//先序遍历整棵树--递归
			if (!compareTree(Node1->right, Node2->right)) {
				return false;
			}
		}
		else {
			return 0;
		}

	}
	else {
		return 1;
	}
}
int main()
{
	int N, L,data;
	search_tree root_first=NULL, root_second=NULL;
	bool isfindroot_first,isfindroot_second;
	while (cin >>N&&N!=0) {
		isfindroot_first = false, isfindroot_second = false;
		cin >> L;
		for (int i = 0; i < L + 1; i++) {
			for (int j = 0; j < N; j++) {
				cin >> data;
				search_tree newNode;
				newNode = (search_tree)malloc(sizeof(search));
				newNode->data = data;
				newNode->left = NULL;
				newNode->right = NULL;
				if (i==0) {//输入第一组模板数据用于与其他组数据比较
					if (!isfindroot_first) {//保存输入的第一个节点,即根结点
						root_first = newNode;
						isfindroot_first = true;
					}
					else {
						InsertNode(root_first,newNode);//将新加入的节点插入二叉搜索树中
					}
				}
				else {
					if (!isfindroot_second) {
						root_second = newNode;
						isfindroot_second = true;
					}
					else {
						InsertNode(root_second, newNode);
					}
				}
			}
			if (isfindroot_second) {//如果第二个根结点找到,说明第二组数据已经输入完毕,接下来就是比较
				int equal=compareTree(root_first, root_second);//比较函数
				if (equal) {
					cout << "Yes" << endl;
				}
				else {
					cout << "No" << endl;
				}
			}
			isfindroot_second = false;//恢复没有找到的状态,用于接收下一组值
		}
	}
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值