树的同构[天梯赛二叉树专项训练]

文章目录

题目描述


cpp 复制代码
输入样例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
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

思路

1.用结构体数组模拟二叉树--由于题目中给定节点值均不相同,因此这种方法可取

2.建树时,存储每棵树的根节点,后序判断是否同构时,从根节点开始判断

3.Compare函数判断两棵树是否同构

①当前两棵树均为空树--同构

②一棵树为空,一棵树不为空--不同构

③两棵树均不为空,但是值不相同--不同构

④除上述三种特殊情况外,进一步递归判断第一棵树和第二棵树的左右孩子是否相同或交叉相等

AC代码

cpp 复制代码
#include <bits/stdc++.h>
using namespace std;
const int N = 15;
typedef struct node
{
    char data;
    int left, right;
}node;
node tree1[N], tree2[N];
bool vis[N];
bool Judge_Num(char x)
{
    return x >= '0' && x <= '9';
}
int Init(node t[])
{
    int n;
    char root, l, r;
    cin >> n;
    if(!n) return -1;
    memset(vis, false, sizeof(vis));
    for(int i = 0; i < n; i ++)
    {
        cin >> root >> l >> r;
        //cout << root << " " << l << " " << r << endl;
        t[i].data = root;
        if(Judge_Num(l))
        {
            int x = l - '0';
            t[i].left = x;
            vis[x] = true;
        }
        else t[i].left = -1;
        if(Judge_Num(r))
        {
            int x = r - '0';
            t[i].right = x;
            vis[x] = true;
        }
        else t[i].right = -1;
    }
    for(int i = 0; i < n; i ++)
    {
        if(!vis[i]) return i;
    }
}

bool Compare(int root1, int root2)
{
    if(root1 == -1 && root2 == -1) return true;
    if((root1 == -1 && root2 != -1) || (root1 != -1 && root2 == -1)) return false;
    if(tree1[root1].data != tree2[root2].data) return false;
    return (Compare(tree1[root1].left, tree2[root2].left) && Compare(tree1[root1].right, tree2[root2].right))
        || (Compare(tree1[root1].left, tree2[root2].right) && Compare(tree1[root1].right, tree2[root2].left)); 
}
int main()
{
    int root1 = Init(tree1);
    int root2 = Init(tree2);
    if(Compare(root1, root2)) cout << "Yes" << endl;
    else cout << "No" << endl;
    return 0;
}

欢迎大家批评指正!!!

相关推荐
方案开发PCBA抄板芯片解密29 分钟前
什么是算法:高效解决问题的逻辑框架
算法
songx_9940 分钟前
leetcode9(跳跃游戏)
数据结构·算法·游戏
学c语言的枫子1 小时前
数据结构——双向链表
c语言·数据结构·链表
小白狮ww1 小时前
RStudio 教程:以抑郁量表测评数据分析为例
人工智能·算法·机器学习
AAA修煤气灶刘哥1 小时前
接口又被冲崩了?Sentinel 这 4 种限流算法,帮你守住后端『流量安全阀』
后端·算法·spring cloud
Boop_wu2 小时前
[数据结构] 栈 · Stack
数据结构
kk”2 小时前
C语言快速排序
数据结构·算法·排序算法
纪元A梦2 小时前
贪心算法应用:基因编辑靶点选择问题详解
算法·贪心算法
3壹2 小时前
数据结构精讲:栈与队列实战指南
c语言·开发语言·数据结构·c++·算法
skytier3 小时前
Construct内报错和定位解决
算法