题目来源:中国大学MOOC-陈越、何钦铭-数据结构-2018春
作者: 陈越
单位: 浙江大学
问题描述:
给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
输入格式:
输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数N (≤10),即该树的结点数(此时假设结点从0到N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。
输出格式:
如果两棵树是同构的,输出“Yes”,否则输出“No”。
输入样例1(对应图1):
8
A 1 2
B 3 4
C 5 -
D - -
E 6 -
G 7 -
F - -
H - -
8
G - 4
B 7 6
F - -
A 5 1
H - -
C 0 -
D - -
E 2 -
输出样例1:
Yes
输入样例2(对应图2):
8
B 5 7
F - -
A 0 3
C 6 -
H - -
D - -
G 4 -
E 1 -
8
D 6 -
B 5 -
E - -
H - -
C 0 2
G - 3
F - -
A 1 4
输出样例2:
No
解答:
判断过程分几种情况讨论
- 两棵树树根均为空,返回同构
- 两棵树中只有一棵树树根为空,返回不同构
- 两棵树中树根数值不同,返回不同构
- 两棵树树根下左节点均为空,递归调用判断右节点
- 两棵树树根下左节点均不为空且相对等,递归调用判断根的左子树与根的右子树
- 剩余情况,递归判断A的左子树与B的右子树,递归判断A的右子树与B的左子树
#include <iostream>
#include <algorithm>
using namespace std;
const int maxn=10;
struct node
{
char letter;
int leftChild;
int rightChild;
};
node treeA[maxn];
node treeB[maxn];
bool ishead[maxn];
int N;
int buildTree(node *tree)
{
cin>>N;
int treeHead=-1;
char childInfo;
fill(ishead,ishead+maxn,true);
for(int i=0;i<N;i++)
{
cin>>tree[i].letter;
cin>>childInfo;
if(childInfo!='-')
{
tree[i].leftChild=childInfo-'0';
ishead[tree[i].leftChild]=false;
}
else
tree[i].leftChild=-1;
cin>>childInfo;
if(childInfo!='-')
{
tree[i].rightChild=childInfo-'0';
ishead[tree[i].rightChild]=false;
}
else
tree[i].rightChild=-1;
}
for(int i=0;i<N;i++)
if(ishead[i])
treeHead=i;
return treeHead;
}
bool isEqual(int headA,int headB)
{
if(headA==-1&&headB==-1)
return true;
if(headA*headB<0)
return false;
if(treeA[headA].letter!=treeB[headB].letter)
return false;
if(treeA[headA].leftChild==-1&&treeB[headB].leftChild==-1)
isEqual(treeA[headA].rightChild,treeB[headB].rightChild);
if((treeA[headA].leftChild!=-1&&treeB[headB].leftChild!=-1)&&(treeA[treeA[headA].leftChild].letter==treeB[treeB[headB].leftChild].letter))
return isEqual(treeA[headA].leftChild,treeB[headB].leftChild)&&isEqual(treeA[headA].rightChild,treeB[headB].rightChild);
else
return isEqual(treeA[headA].rightChild,treeB[headB].leftChild)&&isEqual(treeA[headA].leftChild,treeB[headB].rightChild);
}
int main()
{
int headA=buildTree(treeA);
int headB=buildTree(treeB);
if(isEqual(headA,headB))
cout<<"Yes"<<endl;
else
cout<<"No"<<endl;
return 0;
}
本文介绍了一种算法,用于判断两棵二叉树是否通过有限次左右子树交换成为相同的树。通过输入两棵树的结点信息,利用递归方式判断两棵树是否同构。
2539

被折叠的 条评论
为什么被折叠?



