C语言 树的同构实现

使用静态链表存储二叉树,通过递归方法判断数的同构

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

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

Tree BuildTree(TreeNode T[]);
int Isomorphic(Tree R1, Tree R2);
int main()
{
	Tree R1, R2;
	R1 = BuildTree(T1);
	R2 = BuildTree(T2);
	if (Isomorphic(R1, R2))
		printf("Yes\n");
	else
		printf("No\n");
	return 0;
}

Tree BuildTree(TreeNode T[])
{
	int N;
	char cl, cr;
	int check[MaxTree];       // 判断每一个节点有没有节点指向
	int Root=Null;
	scanf_s("%d\n", &N);
	if (N)
	{
		for (int i = 0; i < N; i++)
			check[i] = 0;
		for (int i = 0; i < N; i++)
		{
			scanf_s("%c %c %c\n", &T[i].Element, &cl, &cr);
			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 (int i = 0; i < N; i++)
		{
			if (!check[i])
			{
				Root = i;
				break;
			}	
		}
	}
	return Root;
}

int Isomorphic(Tree R1, Tree R2)
{
	if (R1 == Null && R2 == Null)
		return 1;
	if ((R1 == Null && R2 != Null) || (R2 != Null && R1 == Null))
		return 0;
	if (T1[R1].Element != T2[R2].Element)
		return 0;
	if ((T1[R1].Left == Null) && (T2[R2].Left == Null))
		return Isomorphic(T1[R1].Right, T2[R2].Right);
	// 不需要交换左右子树
	if (((T1[R1].Left != Null) && (T2[R2].Left != Null)) &&
		((T1[T1[R1].Left].Element) == T2[T2[R2].Left].Element))
	{
		return (Isomorphic(T1[R1].Left, T2[R2].Left))&&
			(Isomorphic(T1[R1].Right, T2[R2].Right));
	}
	// 需要交换左右子数
	else
	{
		return (Isomorphic(T1[R1].Left, T2[R2].Right)) &&
			(Isomorphic(T1[R1].Right, T2[R2].Left));
	}


}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值