03-树1 树的同构 (25 分)

该博客给出了树的同构问题的代码实现。定义了树节点结构体,包含元素、左右子树信息。有构建树和判断同构的函数,在主函数中调用构建树函数获取根节点,再调用同构判断函数输出结果。
#include <cstdio>
#define MaxTree 12
#define ElementType char
#define Null -1
#define Tree int
struct TreeNode {
    ElementType element;
    Tree left;
    Tree right;
}t1[MaxTree], t2[MaxTree];

Tree buildTree(struct TreeNode* t);
int isomorphic(Tree r1, Tree r2);

int main() {
    
    Tree r1, r2;
    
    r1 = buildTree(t1);
    r2 = buildTree(t2);
    if(isomorphic(r1, r2)) printf("Yes\n");
    else printf("No\n");
    
    return 0;
} 

Tree buildTree(struct TreeNode* t) {
    int n, cl, cr, hashT[MaxTree];
    int root = -1;
    scanf("%d", &n);
    if(n) {
        for(int i=0; i<n; i++) hashT[i] = 0;
        for(int i=0; i<n; i++) {
            getchar();
            scanf("%c %c %c", &t[i].element, &cl, &cr);
            if(cl != '-') {
                t[i].left = cl - '0';
                hashT[t[i].left] = 1;
            }
            else t[i].left = Null;
            if(cr != '-') {
                t[i].right = cr - '0';
                hashT[t[i].right] = 1;
            }
            else t[i].right = Null;
                
        }
        for(int i=0; i<n; i++) {
            if( !hashT[i] ) {
                root = i;
                break;
            }
        }
        
    }
    
    return root;
    
}

int isomorphic(Tree r1, Tree r2) {
    if((r1 == Null) && (r2 == Null)) return 1;
    else if((r1 != Null) && (r2 != Null)) {
        if(t1[r1].element != t2[r2].element) return 0;
        if(t1[r1].left == Null && t1[r2].left == Null)
            return (isomorphic(t1[r1].right, t2[r2].right)); 
        else if((t1[r1].left != Null && t2[r2].left != Null) and t1[t1[r1].left].element == t2[t2[r2].left].element) 
            return (isomorphic(t1[r1].left, t2[r2].left) && isomorphic(t1[r1].right, t2[r2].right));
        else return (isomorphic(t1[r1].left, t2[r2].right) && isomorphic(t1[r1].right, t2[r2].left)) ;
    }
    else return 0;
    
    
    
}

 

转载于:https://www.cnblogs.com/acoccus/p/10935571.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值