二叉树的同构

问题描述

给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。
例如下图给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。

这幅图中的两棵树就不是同构的

现给定两棵树,请你判断它们是否是同构的。

输入格式

输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数N (≤10),即该树的结点数(此时假设结点从0到N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。

输出格式

如果两棵树是同构的,输出“Yes”,否则输出“No”。

输入样例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(对应第二幅图)

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

C语言代码

#include <stdio.h>
#include <stdlib.h>
#define maximum 10

typedef struct tnode
{
	char data;
	int lchildren;
	int rchildren;
}tnode;
tnode tree1[maximum], tree2[maximum];

int build(tnode tree[])
{
	int n;
	scanf("%d\n", &n);
	int i, check[n], root = -1;//check数组用于寻找根节点 
	char l, r;
	for(i = 0; i < n; i++) check[i] = 0;
	for(i = 0; i < n; i++) 
	{
		scanf(" %c %c %c", &tree[i].data, &l, &r);
		if(l != '-') 
		{
			tree[i].lchildren = l - '0';
			check[tree[i].lchildren] = 1;
		}
		else tree[i].lchildren = -1;
		if(r != '-')
		{
			tree[i].rchildren = r - '0';
			check[tree[i].rchildren] = 1;
		}
		else tree[i].rchildren = -1;
	}
	//寻找根节点,check数组的值为零说明没有双亲结点 
	for(i = 0; i < n; i++) 
		if(check[i] == 0)
		{
			root = i;
			break;
		}
	return root;
}

int judge(int root1, int root2)
{
	if((root1 == -1) && (root2 == -1)) return 1;//若根节点为空,则同构 
	else if (root1 == -1 && root2 != -1 || root1 != -1 && root2 == -1) return 0;//根节点有一个为空,另一个不空,非同构 
	else if (tree1[root1].data != tree2[root2].data) return 0;//根节点都不空但元素不同,非同构
	//左子树都为空,则判断右子树 
	else if (tree1[root1].lchildren == -1 && tree2[root2].lchildren == -1) return judge(tree1[root1].rchildren, tree2[root2].rchildren);
	//左子树都不空且元素均相等,则判断各子树 
	else if (tree1[root1].lchildren != -1 && tree2[root2].lchildren != -1 && tree1[tree1[root1].lchildren].data == tree2[tree2[root2].lchildren].data)
			return (judge(tree1[root1].lchildren, tree2[root2].lchildren) && judge(tree1[root1].rchildren, tree2[root2].rchildren));
	//左子树有一个为空另一个不空 或者 左子树都不空但元素不等,交换左右子树 
	else return (judge(tree1[root1].lchildren, tree2[root2].rchildren) && judge(tree1[root1].rchildren, tree2[root2].lchildren));
}

int main(int argc, char *argv[]) {
	int n, root1, root2;
	root1 = build(tree1);
	root2 = build(tree2);
	if (judge(root1, root2)) printf("Yes");
	else printf("No");
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章