数据结构与算法题目集|7-3 树的同构 c++满分题解

给定两棵树T1和T2。如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的。例如图1给出的两棵树就是同构的,因为我们把其中一棵树的结点A、B、G的左右孩子互换后,就得到另外一棵树。而图2就不是同构的。

数据结构与算法题目集|7-3 树的同构 c++满分题解_第1张图片

图1

数据结构与算法题目集|7-3 树的同构 c++满分题解_第2张图片

图2

现给定两棵树,请你判断它们是否是同构的。

输入格式:

输入给出2棵二叉树树的信息。对于每棵树,首先在一行中给出一个非负整数N (≤10),即该树的结点数(此时假设结点从0到N−1编号);随后N行,第i行对应编号第i个结点,给出该结点中存储的1个英文大写字母、其左孩子结点的编号、右孩子结点的编号。如果孩子结点为空,则在相应位置上给出“-”。给出的数据间用一个空格分隔。注意:题目保证每个结点中存储的字母是不同的。

输出格式:

如果两棵树是同构的,输出“Yes”,否则输出“No”。

输入样例1(对应图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(对应图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

这题还是有些难度的,我在第一个测试卡了一会,发现原来是自己没有找根节点,然后写了个找根节点的函数就解决了,在写的时候还忘记了map的first和second的用法,还有在new node的时候里面用了小括号写三目运算符,外面没有用大括号。总的来说很绕,值得限时多写几次加深印象:

#include 
#include 
#include 
#include 
using namespace std;

// 结点结构体
struct node {
    char val;   // 结点值
    int left, right;    // 左右子结点的索引
};

// 创建二叉树
unordered_map create(int n) {
    unordered_map st;
    for (int i = 0; i < n; i++) {
        char val;
        string left, right;
        cin >> val >> left >> right;
        // 使用列表初始化创建结点
        st[i] = new node{val, (left == "-" ? -1 : stoi(left)), (right == "-" ? -1 : stoi(right))};
    }
    return st;
}

// 判断两棵树是否同构
bool isomorphic(unordered_map& t1, unordered_map& t2, int root1, int root2) {
    if (!t1[root1] && !t2[root2])   // 如果两棵树均为空,返回 true
        return true;
    if ((!t1[root1] && t2[root2]) || (t1[root1] && !t2[root2]))  // 如果两棵树一个为空一个不为空,返回 false
        return false;
    if (t1[root1]->val != t2[root2]->val)   // 如果根节点值不相等,返回 false
        return false;
    // 递归判断左右子树是否同构
    return (isomorphic(t1, t2, t1[root1]->left, t2[root2]->left) && isomorphic(t1, t2, t1[root1]->right, t2[root2]->right)) ||
           (isomorphic(t1, t2, t1[root1]->left, t2[root2]->right) && isomorphic(t1, t2, t1[root1]->right, t2[root2]->left));
}

// 寻找根节点索引
int findRoot(unordered_map& a) {
    set st;
    // 遍历所有结点,将所有结点的左右子结点索引加入到集合中
    for (auto& p : a) {
        st.insert(p.second->left);
        st.insert(p.second->right);
    }
    // 找到根节点索引
    for (int i = 0; i < a.size(); i++) {
        if (st.find(i) == st.end())
            return i;
    }
    return -1; // 如果没有找到根节点,返回 -1
}

int main() {
    int n1, n2;
    cin >> n1;
    // 创建两棵树
    unordered_map t1 = create(n1);
    cin >> n2;
    unordered_map t2 = create(n2);
    // 寻找根节点索引
    int root1 = findRoot(t1);
    int root2 = findRoot(t2);

    // 判断两棵树是否同构,并输出结果
    if (isomorphic(t1, t2, root1, root2)) {
        cout << "Yes";
    } else {
        cout << "No";
    }

    // 释放内存
    for (auto& pair : t1) {
        delete pair.second;
    }
    for (auto& pair : t2) {
        delete pair.second;
    }

    return 0;
}

你可能感兴趣的:(pta数据结构与算法题目集,c++,算法,开发语言)