03-树1 树的同构

在这里插入图片描述在这里插入图片描述

思路:基本参照慕课上的浙大数据结构思路来,判断同构的函数处做了一些小修改

代码如下

#include <iostream>
using namespace std;

typedef struct tree{
	char ch;
	int Left, Right; 
}Tree;
Tree T1[10], T2[10];

int CreatTree(Tree T[]);
bool Isomorphic(int r1, int r2);

int main() {
	int R1, R2;
	R1 = CreatTree(T1);
	R2 = CreatTree(T2);
	if(Isomorphic(R1, R2)) printf("Yes"); 
	else printf("No");
} 

int CreatTree(Tree T[]) {
	int N; scanf("%d\n", &N);
	int check[10] = {0};
	int Root = -1;				//表示根节点下标 
	for(int i = 0; i < N; i++) {
		char cl, cr;
		scanf("%c %c %c\n", &T[i].ch, &cl, &cr);
		if('-' == cl) T[i].Left = -1;
		else {
			T[i].Left = cl-'0';
			check[T[i].Left] = 1;
		}
		if('-' == cr) T[i].Right = -1;
		else {
			T[i].Right = cr-'0';
			check[T[i].Right] = 1;
		}
	}
	for(int i = 0; i < N; i++)
		if(0 == check[i]) {Root = i; break;}
	return Root;
}

bool Isomorphic(int R1, int R2) {
	if(-1 == R1 && -1 == R2) return true;				//都是空树,同构
	else if((-1 == R1)&&(-1 != R2) || (-1 == R2)&&(-1 != R1) || (T1[R1].ch != T2[R2].ch))
		return false; 									//只有一棵树空或者根不同,不同构
	else if(-1 == T1[R1].Left && -1 == T2[R2].Left) 	//都没有左子树,只需比较右子树
		return Isomorphic(T1[R1].Right, T2[R2].Right);
	else if(-1 == T1[R1].Right && -1 == T2[R2].Right) 	//都没有右子树,只需比较左子树
		return Isomorphic(T1[R1].Left, T2[R2].Left);
	else if(T1[T1[R1].Left].ch == T2[T2[R2].Left].ch)	//左子树数据相同,即不需要交换左右子树,递归判断左右子树是否同构
		return Isomorphic(T1[R1].Left, T1[R2].Left) && Isomorphic(T1[R1].Right, T1[R2].Right);
	else												//需要交换左右子树再判断是否同构	
		return Isomorphic(T1[R1].Left, T2[R2].Right) && Isomorphic(T1[R1].Right, T2[R2].Left);
}

反馈:

  1. scanf读入字符时,空格和\n可以直接代替输入中的空格与回车,无需添加getchar()读走空白字符
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值