您的位置:首页 > 理论基础 > 数据结构算法

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

2018-03-03 13:36 316 查看


解题思路:首先保存输入的第一组数据,该组数据与其他组信息比较,在输入数据时保存数据的根结点,根据根结点构造树,递归比较两棵树的元素大小。#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;
}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  数据结构 PTA