树的同构[天梯赛二叉树专项训练]-AC代码

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

欢迎大家批评指正!!!

上一篇:mysql 正则表达式查询


下一篇:【Android、 kotlin】kotlin学习笔记