PTA树的同构 DFS道路选择

#include <bits/stdc++.h>
using namespace std;

struct Node {
    char data;
    int l, r;
}lt[105], rt[105];
//记录左树和右树
int _list[105] = {0};
//记录该节点是否有父节点

int build(int n, Node tree[]) {
    memset(_list, 0, sizeof _list);
    for (int i = 0; i < n; ++i) {
        char a, b, c;
        cin >> a >> b >> c;
        tree[i].data = a;

        if (b != '-') {
            tree[i].l = b - '0';
            _list[tree[i].l] = 1;
        }
        else {
            tree[i].l = -1;
        }
        if (c != '-') {
            tree[i].r = c - '0';
            _list[tree[i].r] = 1;
        }
        else {
            tree[i].r = -1;
        }
    }
    //求根节点
    int root = -1;
    for (int i = 0; i < n; ++i) {
        if (tree[i].data != 0 and _list[i] != 1) {
            root = i;
            break;
        }
    }

    return root;
}

bool judge(int lroot, int rroot) {
    if (lroot == -1 and rroot == -1) {
        return true;
    }
    if ((lroot == -1 and rroot != -1) or (lroot != -1 and rroot == -1)) {
        //两边不对称
        return false;
    }
    if (lt[lroot].data != rt[rroot].data) {
        return false;
    }
    if (lt[lroot].l == -1 and rt[rroot].l == -1) {
        //两棵树左子树都为空
        return judge(lt[lroot].r, rt[rroot].r);
    }
    if (lt[lroot].l != -1 and rt[rroot].l != -1 and lt[lt[lroot].l].data == rt[rt[rroot].l].data) {
        //两个左子树都不为空,且左子节点的值都相同
        return judge(lt[lroot].l, rt[rroot].l) and  judge(lt[lroot].r, rt[rroot].r);
    }
    else {
        //否则其他情况都交换左右子节点的比较次序
        return judge(lt[lroot].l, rt[rroot].r) and judge(lt[lroot].r, rt[rroot].l);
    }
}

int main() {
#ifndef ONLINE_JUDGE
    freopen("D:/VS CODE/C++/in.txt", "r", stdin);
    freopen("D:/VS CODE/C++/out.txt", "w", stdout);
#endif
    int n1, n2;

    cin >> n1;
    int root1 = build(n1, lt);

    cin >> n2;
    int root2 = build(n2, rt);

    bool ans;
    ans = judge(root1, root2);
    if (ans)
        cout << "Yes";
    else 
        cout << "No";
    fclose(stdin);
    fclose(stdout);
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值