数据结构实验之二叉树一:树的同构

    xiaoxiao2025-02-05  15

    题目描述

    给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。

    图1

     

    图2

    现给定两棵树,请你判断它们是否是同构的。

    输入

      输入数据包含多组,每组数据给出 2 棵二叉树的信息。对于每棵树,首先在一行中给出一个非负整数 N ( 10) ,即该树的结点数(此时假设结点从 0 N−1 编号);随后 N 行,第 i 行对应编号第 i 个结点,给出该结点中存储的 1 个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出 ”-” 。给出的数据间用一个空格分隔。 注意:题目保证每个结点中存储的字母是不同的。

    输出

      如果两棵树是同构的,输出“ Yes ”,否则输出“ No ”。

    示例输入

    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 -

    示例输出

    Yes

    提示

    测试数据对应图1

    来源

     xam

    示例程序

      #include <iostream> #include <stdlib.h> #include <string.h> #include <stdio.h> using namespace std; struct node { char data; struct node * l; struct node * r; }; struct thing //定义一个结构体用来存放收集到节点和它左右子树的位置 { char ch; int lc; int rc; }a[15]; //建立一棵二叉树 struct node * creat(int x) { struct node * p; p = (struct node *)malloc(sizeof(struct node)); p->l = NULL; p->r = NULL; p->data = a[x].ch; if(a[x].lc != -1) //当收集到此时节点的左子树不为空,递归根据左子树的序号找到它的左子树,并插入 p->l = creat(a[x].lc); if(a[x].rc != -1) //当收集到此时节点的右子树不为空,递归根据右子树的序号找到它的右子树,并插入 p->r = creat(a[x].rc); return p; }; //收集输入的数据,调用creat()建立一棵二叉树 struct node * build(int n) { int j; bool sign[15]; memset(sign, false, sizeof(sign)); //定义一个布尔类型的判断数组,VC可以用整形以0和1判断 for(int i = 0; i < n; i++) { char c1, c2, c3; cin >> c1 >> c2 >> c3; a[i].ch = c1; if(c2 == '-') //当c2为—的时候,也就是它的左子树为空,因为此时 //并不是树结构,所以将字符转换为-1存入到中间结构体中,用于creat()的建树 a[i].lc = -1; else { a[i].lc = c2 - '0'; //当c2不为-的时候,也就是说它的左子树不为空,同上 sign[a[i].lc] = true; //通过标记变量的真假,来找出根节点 } if(c3 == '-') a[i].rc = -1; else { a[i].rc = c3 - '0'; sign[a[i].rc] = true; } } if(n != 0) { for(j = 0; j < n; j++) //遍历所有的布尔数组,当遇到false跳出,此时的j的值也就是根节点的值 { if(sign[j] == false) break; } } struct node * tree1 = creat(j); return tree1; } int cmp(struct node * tree1, struct node * tree2) { if(tree1 == NULL && tree2 == NULL) //当两棵树都为空树的时候同构 return 1; if(tree1 != NULL && tree2 != NULL) //若树不为空的时候同构,首先满足它们的根节点相同,若根节点相同,则有以下几种情况同构 //1.树1的左子树和树2的左子树相同,并且右子树和右子树相同 //2.树1的左子树和树2的右子树相同,并且右子树和左子树相同 { if(tree1->data == tree2->data) { if((cmp(tree1->l, tree2->l) && cmp(tree1->r, tree2->r)) || (cmp(tree1->l, tree2->r) && cmp(tree1->r, tree2->l))) return 1; } } return 0; } int main() { int n, m; struct node * tree1, * tree2; while(cin >> n) { tree1 = build(n); cin >> m; tree2 = build(m); int flag = cmp(tree1, tree2); if(flag == 0) cout << "No" << endl; else cout << "Yes" << endl; } return 0; }
    转载请注明原文地址: https://ju.6miu.com/read-1296134.html
    最新回复(0)