7-3-树的同构-编程题
程序员文章站
2022-06-07 21:45:22
...
解题代码
#include<stdio.h>
#include<stdlib.h>
typedef enum{false,true} bool;
typedef struct TNode* Tree;
struct TNode {
char Data;
int Left;
int Right;
};
Tree newTree(int N, int* r);
bool Judge(Tree T1, Tree T2, int r1, int r2);
int main()
{
int N1,N2;//number of TNode
int r1=-1, r2=-1;//root of Tree
scanf("%d", &N1);
Tree T1 = newTree(N1,&r1);
scanf("%d", &N2);
Tree T2 = newTree(N2,&r2);
if (Judge(T1, T2, r1, r2)) printf("Yes");
else printf("No");
return 0;
}
Tree newTree(int N,int* r) {
if (!N) return NULL;
Tree T = (Tree)malloc(10 * sizeof(struct TNode));
char tleft, tright, tdata;
int i;
int check[10] = { 0 };
for (i = 0; i < N; i++) {
getchar();
scanf("%c %c %c", &tdata, &tleft, &tright);
T[i].Data = tdata;
if (tleft == '-') T[i].Left = -1;
else {
T[i].Left = tleft - '0';
check[T[i].Left] = 1;
}
if (tright == '-') T[i].Right = -1;
else {
T[i].Right = tright - '0';
check[T[i].Right] = 1;
}
}
for (i = 0; i < N; i++) {
if (!check[i]) break;
}
*r = i;
return T;
}
bool Judge(Tree T1, Tree T2, int r1, int r2) {
if (r1 == -1 && r2 == -1) return true;
if (r1 == -1 && r2 != -1 || r1 != -1 && r2 == -1) return false;
if (T1[r1].Data != T2[r2].Data) return false;
if (T1[r1].Left == -1 && T2[r2].Left == -1) return Judge(T1, T2, T1[r1].Right, T2[r2].Right);
else if(T1[r1].Left!=-1&&T2[r2].Left!=-1&&T1[T1[r1].Left].Data==T2[T2[r2].Left].Data) return Judge(T1, T2, T1[r1].Right, T2[r2].Right);
else return Judge(T1, T2, T1[r1].Left, T2[r2].Right) && Judge(T1, T2, T1[r1].Right, T2[r2].Left);
}
测试结果
问题整理
1.关于迭代中的return:只要迭代过程中,迭代函数出现在了return后边,那所有的if出口都要跟上return以便使迭代函数在任何情况下都有明确的赋值。
上一篇: 堆栈和队列互相模拟
推荐阅读
-
Java编程基于快速排序的三个算法题实例代码
-
Python编程实现双链表,栈,队列及二叉树的方法示例
-
图论小结(一)包括一些最短路,最小生成树,差分约束,欧拉回路,的经典题和变种题。强连通,双连通,割点割桥的应用。二分匹配
-
荐 Java刷题笔记15:不同的二叉搜索树( Unique Binary Search Trees)
-
Python编程小练习 | 算法题:津巴布韦的鸡蛋价格
-
分享3道关于面试中会遇到的python的编程题,附题解
-
[算法练习-剑指offer]题18.二叉树的镜像(Java)
-
BZOJ4337: BJOI2015 树的同构(hash 树同构)
-
Python编程求解二叉树中和为某一值的路径代码示例
-
荐 非常经典的java编程题全集-共50题(1-10)