【数据结构】树的同构

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 <iostream>
#include <cstdio>
#include <cstring>

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值