树1——树的同构
来源:互联网 发布:手机淘宝网店怎么装修 编辑:程序博客网 时间:2024/06/04 18:25
给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。
图1
图2
现给定两棵树,请你判断它们是否是同构的。
输入格式:
输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数NNN (≤10\le 10≤10),即该树的结点数(此时假设结点从0到N−1N-1N−1编号);随后NNN行,第iii行对应编号第iii个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。
输出格式:
如果两棵树是同构的,输出“Yes”,否则输出“No”。
输入样例1(对应图1):
8A 1 2B 3 4C 5 -D - -E 6 -G 7 -F - -H - -8G - 4B 7 6F - -A 5 1H - -C 0 -D - -E 2 -
输出样例1:
Yes
输入样例2(对应图2):
8B 5 7F - -A 0 3C 6 -H - -D - -G 4 -E 1 -8D 6 -B 5 -E - -H - -C 0 2G - 3F - -A 1 4
输出样例2:
No
#include <stdio.h>#define MaxTree 10#define Null -1typedef int Tree ;typedef char ElementType ;typedef struct TreeNode TreeNodeArray ;struct TreeNode{ ElementType Element ; Tree Left ; Tree Right ;} ;struct TreeNode Tree1[MaxTree] , Tree2[MaxTree] ;Tree BuildeTree( TreeNodeArray Tree[] ){ int i,N,check[MaxTree] ; char cl,cr ; int Root ; scanf("%d",&N ) ; if( N!=0 ) { for( i=0 ; i<N ; i++ ) check[i] = 0 ; for( i=0 ; i<N ; i++ ) { scanf(" %c %c %c" , &Tree[i].Element , &cl , &cr ) ;//scanf("%c %c %c\n" , &Tree[i].Element , &cl , &cr ) ; if( cl != '-' ) { Tree[i].Left = cl-'0' ; check[ Tree[i].Left ] = 1 ; } else Tree[i].Left = Null ; if( cr!= '-' ) { Tree[i].Right = cr-'0' ; check[ Tree[i].Right ] =1 ; } else Tree[i].Right = Null ; } } else return Null ; for(i=0 ; i<N ; i++ ) { if(check[ i ]==0 ) break ; } Root = i ; return Root ;}int Isomorphic( Tree Root1,Tree Root2 ){ if( (Root1== Null) && (Root2== Null) ) return 1 ; if( ((Root1== Null)&&(Root2!= Null)) || ((Root1!= Null)&&(Root2 == Null)) ) return 0 ; if( Tree1[Root1].Element != Tree2[Root2].Element ) return 0 ; if( (Tree1[Root1].Left == Null) && (Tree2[Root2].Left== Null) ) return Isomorphic( Tree1[Root1].Right,Tree2[Root2].Right ) ; if( ((Tree1[Root1].Left!= Null) && (Tree2[Root2].Left!= Null))&& (( Tree1[ Tree1[Root1].Left ].Element==Tree2[Tree2[Root2].Left].Element )) ) return ( Isomorphic(Tree1[Root1].Left,Tree2[Root2].Left) && Isomorphic( Tree1[Root1].Right,Tree2[Root2].Right ) ) ; return( Isomorphic( Tree1[Root1].Left,Tree2[Root2].Right ) && Isomorphic( Tree1[Root1].Right,Tree2[Root2].Left ) ) ;}int main( ){ int i ; Tree Root1 , Root2 ; Root1 = BuildeTree( Tree1 ) ; Root2 = BuildeTree( Tree2 ) ; if( Isomorphic( Root1,Root2 ) ) printf("Yes\n") ; else printf("No\n") ; return 0 ;}
0 0
- 树1——树的同构
- 数据结构——树的同构
- 同构树的判别
- 树的同构
- SDUTOJ 树的同构
- 树的同构
- 树的同构
- pta--树的同构
- 判断树的同构
- 树的同构
- 树的同构
- 树的同构
- 数据结构--树的同构
- 树的同构
- 树的同构
- PTA 树的同构
- PTA-树的同构
- 树的同构
- Volley的使用(一)
- 文章标题
- 小波变换理论讲解
- 第三次上机实践项目-项目1-最大公约数
- 解决double和float精度不准的问题
- 树1——树的同构
- LA4726(数形结合 & 单调队列)
- POJ 2230 Watchcow (欧拉回路)
- 顺序表的初始化(常见用法)
- java文件的读写
- 树2——List Leaves
- Ubuntu系统中安装RPM格式包的方法
- while(1) 什么意思 while(i--)什么意思?
- JavaWeb开发之六:HttpServletRequest对象