【数据结构】树的同构

文章目录

    • [100. 相同的树](https://leetcode-cn.com/problems/same-tree/)
    • [7-3 树的同构 (25分)](https://pintia.cn/problem-sets/15/problems/711)

100. 相同的树

算法:递归判断

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool isSameTree(TreeNode* p, TreeNode* q) {
        if(p == NULL && q == NULL) return true; // 双空
        if(p == NULL || q == NULL) return false; // 有一个为空

        if(p->val != q->val) return false;
        else return isSameTree(p->left,q->left) && isSameTree(p->right,q->right); // 递归判断左子树和右子树
    }
};

7-3 树的同构 (25分)

比上一题复杂一点,可以交换左右子树

#include 
#include 
#include 

using namespace std;

const int N = 11;

struct Tree{
    char val;
    int left;
    int right;
}t1[N],t2[N];
bool d[N]; // 入度,根节点入度为0

int build(Tree t[])
{
    memset(d,0,sizeof d);
    int root = -1;
    int n;
    cin >> n;
    for(int i=0;i<n;i++)
    {
        char a,b,c;
        cin >> a >> b >> c;
        t[i].val = a;
        if(b=='-') t[i].left = -1;
        else t[i].left = b-'0', d[b-'0'] = 1;
     
        if(c=='-') t[i].right = -1;
        else t[i].right = c-'0', d[c-'0'] = 1;
    }
    
    for(int i=0;i<n;i++)
       if(!d[i]) root = i;
    return root;
}

bool isSameTree(int r1,int r2)
{
    if(r1 == -1 && r2 == -1) return true; // 两边为空
    if((r1 == -1 && r2 != -1) || (r1 != -1 && r2 == -1)) return false; // 有一个为空
    if(t1[r1].val != t2[r2].val ) return false; // 值不同
    if(t1[r1].left == -1 && t2[r2].left == -1) return isSameTree(t1[r1].right,t2[r2].right); // 没有左子树
    
    if(t1[r1].left != -1 && t2[r2].left !=-1 && t1[t1[r1].left].val == t2[t2[r2].left].val) //不需要交换左右子树
        return isSameTree(t1[r1].left,t2[r2].left) && isSameTree(t1[r1].right,t2[r2].right);
    else // 需要交换左右子树
        return isSameTree(t1[r1].left,t2[r2].right) && isSameTree(t1[r1].right,t2[r2].left);
    
}

int main()
{
    int root1 = build(t1);
    int root2 = build(t2);
 
    if(isSameTree(root1,root2)) puts("Yes");
    else puts("No");
    
    return 0;
}

你可能感兴趣的:(数据结构)