陈越《数据结构》第三讲 树(上)
3.1 树与树的表示3.1.1 查找的方法
3.1.2 树
3.2 二叉树及存储结构
3.3 二叉树的遍历
3.4 小白专场:树的同构程序: //输入样例1(对应图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(对应图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
//给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。
//author: Paul-Huang
//data: 18/6/2017
#include<stdio.h>
#include <stdlib.h>
#include<process.h>//引入头文件
#define MaxTree 10
#define Null -1
#define ElementType char
#define Tree int
//建立动态链表
struct TreeNode
{
ElementType node;
Tree Left;
Tree Right;
}Tree1[MaxTree],Tree2[MaxTree];
Tree BuildTree(struct TreeNode T[]);
int Isomprphic(Tree root1,Tree root2);
int main()
{
Tree R1,R2;
R1 = BuildTree(Tree1);
R2 = BuildTree(Tree2);
if (Isomprphic(R1,R2)){
printf("Yesn");
}
else{
printf("Non");
}
system("pause");//暂停往下执行 按下任意键继续
return 1;
}
Tree BuildTree(struct TreeNode T[])
{
Tree check[MaxTree],Root = Null; //root = Null 空树则返回Null
char cl,cr;
int i,N;
scanf("%dn",&N);
if (N) {
for ( i = 0; i < N; i++)
check[i] = 0;
//输入数值,并建立链表
for (i = 0; i < N; i++)
{
scanf("%c %c %cn",&T[i].node,&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 (i = 0; i < N; i++)
if (!check[i])
break;
Root = i;
}
return Root;
}
int Isomprphic(Tree root1,Tree root2)
{
if ((root1 == Null) && (root2 == Null))/* both empty */
return 1;
if (((root1 == Null) && (root2 != Null)) || ((root1 != Null) && (root2 == Null)))
return 0;/* one of them is empty */
if (Tree1[root1].node != Tree2[root2].node)
return 0; /* roots are different */
if ((Tree1[root1].Left == Null) && (Tree2[root2].Left == Null))
/* both have no left subtree */
return Isomprphic(Tree1[root1].Right,Tree2[root2].Right);
if ((Tree1[root1].Right == Null) && (Tree2[root2].Right == Null))
/* both have no right subtree */
return Isomprphic(Tree1[root1].Left,Tree2[root2].Left);
if ((Tree1[root1].Left != Null) && (Tree2[root2].Left != Null) &&
((Tree1[Tree1[root1].Left].node) == (Tree2[Tree2[root2].Left].node)))
/* no need to swap the left and the right */
return (Isomprphic(Tree1[root1].Left,Tree2[root2].Left)&&
Isomprphic(Tree1[root1].Right,Tree2[root2].Right));
else/* need to swap the left and the right */
return (Isomprphic(Tree1[root1].Left,Tree2[root2].Right) &&
Isomprphic(Tree1[root1].Right,Tree2[root2].Left));
} (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |