树的同构(顺序存储结构)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#define MaxTree 10
#define ElementType char
#define Tree int
#define Null -1

struct TreeNode
{
	ElementType Data;
	Tree Left;
	Tree Right;
}T1[MaxTree], T2[MaxTree];

int main()
{
	Tree R1, R2;
	R1 = BuildTree(T1);
	R2 = BuildTree(T2);
	if (Isomorphic(R1, R2)) printf("Yes\n");
	else printf("No\n");
	system("pause");
	return 0;
}
Tree BuildTree(struct TreeNode T[])
{
	int N;
	scanf("%d", &N);
	if (N == 0)
		return Null;
	getchar();
	int check[MaxTree]={0};
	int i = 0;
	char cl, cr;
	for (i = 0; i < N; i++)
	{
		//cl 跟 cr 输入的是指向左右的下标
		scanf("%c %c %c", &T[i].Data, &cl, &cr);
		getchar();
		if (cl != '-')
		{
			T[i].Left = cl - '0';
			check[T[i].Left] = 1;
		}
		else
		{
			T[i].Left = Null;
		}
		if (cr != '-')
		{
			T[i].Right = cr - '0';
			check[T[i].Right] = 1;
		}
		else
		{
			T[i].Right = Null;
		}
	}
	for (i = 0; i < N; i++)
	{
		if (check[i] == 0)break;
	}
	//返回根
	return i;
}
int Isomorphic(Tree R1, Tree R2)
{
	if (R1 == Null && R2 == Null)return 1;
	if ((R1 == Null && R2 != Null) || (R1 != Null && R2 == Null))return 0;
	if (T1[R1].Data != T2[R2].Data)return 0;
	if (T1[R1].Left == Null && T2[R2].Left == Null)return Isomorphic(T1[R1].Right, T2[R2].Right);
	if (T1[R1].Right == Null && T2[R2].Right == Null)return Isomorphic(T1[R1].Left, T2[R2].Left);
	if ((T1[R1].Left != Null && T2[R2].Left != Null) && (T1[T1[R1].Left].Data == T2[T2[R2].Left].Data))
		return Isomorphic(T1[R1].Left, T2[R2].Left) && Isomorphic(T1[R1].Right, T2[R2].Right);
	else
		return Isomorphic(T1[R1].Right, T2[R2].Left) && Isomorphic(T1[R1].Left, T2[R2].Right);
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值