5-3 树的同构 (25分)

#include <iostream>
#include <string.h>

using namespace std;

struct node
{
	int lchild, rchild;
	char key;
}tree1[10], tree2[10];

int flag[10];

int getindex(char ch)
{
	if(ch == '-')
	{
		return -1;
	}

	return ch - '0';
}

int getroot(int n)
{
	int i;
	for(i = 0; i < n; i++)
	{
		if(flag[i] == 0)
		{
			return i;
		}
	}

	return -1;
}

int buildtree(node tree[])
{
	int n;
	scanf("%d", &n);

	if(n == 0)
	{
		return -1;
	}
	
	memset(flag, 0, sizeof(flag));

	int i;
	char a, b, key;

	for(i = 0; i < n; i++)
	{
		getchar();
		scanf("%c %c %c", &key, &a, &b);

		tree[i].key = key;

		tree[i].lchild = getindex(a);
		flag[tree[i].lchild] = 1;

		tree[i].rchild = getindex(b);
		flag[tree[i].rchild] = 1;
	}

	return getroot(n);
}

int judge(int a, int b)
{
	if(a == -1 && b == -1)
	{
		return 1;
	}
	if(a == -1 || b == -1)
	{
		return 0;
	}
	if(tree1[a].key != tree2[b].key)
	{
		return 0;
	}

	if(tree1[a].lchild == -1 && tree2[b].lchild == -1)
	{
		return judge(tree1[a].rchild, tree2[b].rchild);
	}

	if(tree1[a].lchild != -1 && tree2[b].lchild != -1 && tree1[tree1[a].lchild].key == tree2[tree2[b].lchild].key)
	{
		return judge(tree1[a].lchild, tree2[b].lchild) && judge(tree1[a].rchild, tree2[b].rchild);
	}
	else
	{
		return judge(tree1[a].lchild, tree2[b].rchild) && judge(tree1[a].rchild, tree2[b].lchild);
	}
}

int main()
{
	int a, b;
	a = buildtree(tree1);
	b = buildtree(tree2);

	if(judge(a, b) == 1)
	{
		printf("Yes\n");
	}
	else
	{
		printf("No\n");
	}

	system("pause");
	return 0;
}

 

posted on 2025-11-29 14:55  王景迁  阅读(0)  评论(0)    收藏  举报

导航