【数据结构】C++实现判断两颗二叉树是否同构

参考陈越姥姥数据结构,思路仅供参考

#include <iostream>
#include <string>
#include <vector>
#include <unordered_set>
using namespace std;

struct TreeNode{
    
    
    // int val;
    string name;
    TreeNode* left;
    TreeNode* right;
    TreeNode() {
    
    
        left = right = NULL;
    }
};

TreeNode* gen_tree(vector<string>& names, vector<vector<int>>& info, int root_pos) {
    
    
    TreeNode* root = new TreeNode;
    root->name = names[root_pos];

    int pos_left = info[root_pos][0];
    int pos_right = info[root_pos][1];


    if(pos_left!=-1)
        root->left = gen_tree(names, info, pos_left);
    if(pos_right!=-1)
        root->right = gen_tree(names, info, pos_right);

    return root;
}

TreeNode* build_bt(int n) {
    
    
    string s;
    getline(cin, s);        // 消除缓存
    vector<string> names;
    vector<vector<int>> info(n, vector<int>(2, 0));

    unordered_set<int> sets;        // 用于找root
    for(int i=0; i<n; i++)
        sets.insert(i);

    for(int i=0; i<n; i++) {
    
    
        getline(cin, s);
        s += ' ';
        int left = 0;
        int j = 0;
        while(s.find(' ')!=-1) {
    
    
            int pos = s.find(' ');
            string tmp = s.substr(left, pos-left);
            if(j==0) {
    
    
                names.push_back(tmp);
            }
            else {
    
    
                if(tmp=="-")
                    info[i][j-1] = -1;
                else {
    
    
                    int num = atoi(tmp.c_str());
                    info[i][j-1] = num;
                    sets.erase(num);
                }
            }
            j++;
            s[pos] = '*';
            left = pos + 1;
        }
    }

    int root_pos = *(sets.begin());
    TreeNode* bt1 = gen_tree(names, info, root_pos);
    
    return bt1;
}

bool check_tonggou(TreeNode* root1, TreeNode* root2) {
    
    
    if(!root1 && !root2)
        return true;
    else if((root1 && !root2) || (!root1 && root2))
        return false;
    else {
    
    
        if(root1->name == root2->name) {
    
    
            return (check_tonggou(root1->left, root2->left) && check_tonggou(root1->right, root2->right))
                || ( check_tonggou(root1->left, root2->right) && check_tonggou(root1->right, root2->left));
        }
        else
            return false;
    }
}

int main()
{
    
    
    int n;
    cin >> n;
    TreeNode* bt1 = build_bt(n);

    int m;
    cin >> m;
    TreeNode* bt2 = build_bt(m);

    if(check_tonggou(bt1, bt2))
        cout << "两棵树同构" << endl;
    else
        cout << "两棵树不同构" << endl;


    return 0;
}

实例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 -

实例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

猜你喜欢

转载自blog.csdn.net/ayitime/article/details/126973527