zoukankan      html  css  js  c++  java
  • PAT-树的同构

    链接

    树的同构

    题意

    同构的定义: 给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。

    给两棵树,判断是否同构

    做法

    先建树,然后判断,知道怎么判断就知道怎么写了,具体实现看代码

    代码

    /*
        Name: hello world.cpp
        Author: AA
        Description: 唯代码与你不可辜负
    */
    #include<bits/stdc++.h>
    using namespace std;
    #define LL long long
    #define maxn 20100
    typedef struct Node {
        char data;
        int left;
        int right;
    } Tree;
    Tree t1[maxn], t2[maxn];
    int build(Tree  T[]) {
        int n, cherk[maxn], root = -1;
        char cl, cr;
        scanf("%d", &n);
        getchar();
        if(n) {
            for(int i = 0; i < n; i++)
                cherk[i] = 0;
            for(int i = 0; i < n; i++) {
                scanf("%c %c %c", &T[i].data, &cl, &cr);
                getchar();
                if(cl != '-') {
                    T[i].left = cl - '0';
                    cherk[T[i].left] = 1;
                } else
                    T[i].left = -1;
                if(cr != '-') {
                    T[i].right = cr - '0';
                    cherk[T[i].right] = 1;
                } else
                    T[i].right = -1;
            }
            for(int i = 0; i < n; i++) {
                if(cherk[i] == 0) {
                    root = i;
                    break;
                }
            }
        }
        return root;
    }
    bool Isomorphic(int root1, int root2) {
        if(root1 == -1 && root2 == -1) return true;//都是空的,符合
        else if((root1 == -1 && root2 != -1) || (root1 != -1 && root2 == -1)) return false; //一个空一个不空当然不符合
        else if(t1[root1].data != t2[root2].data) return false; //元素不相等不符合
        else if(t1[root1].left == -1 && t2[root2].left == -1) //左子树都是空的话,就判断右子树
            return Isomorphic(t1[root1].right, t2[root2].right);
        else if(t1[t1[root1].left].data == t2[t2[root2].left].data)//左子树的元素都相同的话就把他们的左右子树都判断
            return (Isomorphic(t1[root1].left, t2[root2].left) && Isomorphic(t1[root1].right, t2[root2].right));
        else //最后是把左右子树交换来判断
            return (Isomorphic(t1[root1].left, t2[root2].right) && Isomorphic(t1[root1].right, t2[root2].left));
    }
    int main() {
        int root1, root2;
        root1 = build(t1);
        root2 = build(t2);
        if(Isomorphic(root1, root2))
            puts("Yes");
        else
            puts("No");
    }
    
  • 相关阅读:
    第四十七讲 ASP.NET实例编程(六)
    第四十四讲 ASP.NET实例编程(三)
    第四十一讲 ASP.NET消息处理(二)
    第四十三讲 ASP.NET实例编程(二)
    第四十二讲 ASP.NET实例编程(一)
    第四十六讲 ASP.NET实例编程(五)
    第四十八讲 ASP.NET实战编程(一)
    第四十讲 ASP.NET消息处理(一)
    第四十五讲 ASP.NET实例编程(四)
    第三十九 ASP.NET编码
  • 原文地址:https://www.cnblogs.com/zhien-aa/p/6651993.html
Copyright © 2011-2022 走看看