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

文章目录

题目描述


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;
}

欢迎大家批评指正!!!

相关推荐
小赵起名困难户1 小时前
蓝桥杯备赛1-2合法日期
算法
shichaog1 小时前
腿足机器人之八- 腿足机器人动力学
算法·机器人
悄悄敲敲敲3 小时前
C++:dfs习题四则
c++·算法·深度优先
牛大了20235 小时前
[LeetCode力扣hot100]-二叉树相关手撕题
算法·leetcode·职场和发展
ll7788115 小时前
LeetCode每日精进:20.有效的括号
c语言·开发语言·算法·leetcode·职场和发展
德先生&赛先生5 小时前
LeetCode-633. 平方数之和
数据结构·算法·leetcode
coding_rui7 小时前
链表(C语言版)
c语言·数据结构·链表
coding_rui7 小时前
哈希表(C语言版)
c语言·数据结构·散列表
coding_rui7 小时前
二叉树(C语言版)
c语言·数据结构
mengyoufengyu7 小时前
算法12-贪心算法
python·算法·贪心算法