Isomorphic:二叉树同构

 如果T1可以通过交换T1中(一些)节点的左右子节点来转换为T2,则T1和T2这两棵树是同构的。例如,图1中的两棵树是同构的,因为如果交换了A、B和G的子节点,而不是其他节点,则它们是相同的。给出一个多项式时间算法来判断两棵树是否同构。

如果T1和T2确实是同构的,函数应该返回1,如果不是,则返回0。

Sample program of judge:

#include <stdio.h>
#include <stdlib.h>

typedef char ElementType;

typedef struct TreeNode *Tree;
struct TreeNode {
    ElementType Element;
    Tree  Left;
    Tree  Right;
};

Tree BuildTree(); /* details omitted */

int Isomorphic( Tree T1, Tree T2 );

int main()
{
    Tree T1, T2;
    T1 = BuildTree();
    T2 = BuildTree();
    printf(“%d\n”, Isomorphic(T1, T2));
    return 0;
}

/* Your function will be put here */

int Isomorphic( Tree T1, Tree T2 )
{
    if(!T1&&!T2)//如果两棵树都是空树,两棵树同构
        return 1;
        
    if(!T1&&T2)  //一棵树为空一棵树不为空,不同构
        return 0;
    if(T1&&!T2)
        return 0;
    if(T1->Element!=T2->Element) //两棵树的数据不同,不同构
        return 0;
    
    if(!T1->Left&&!T2->Left)//两棵树的左子树都为空,判断右子树是不是同构
    return Isomorphic(T1->Right,T2->Right);
    
    //两棵树都有左子树,并且数据都相等,判断两个书是否同构
    if((T1->Left&&T2->Left)&&(T1->Left->Element==T2->Left->Elemrnt))
    return Isomorphic(T1->Left,T2->Left)&&Isomorphic(T1->Right,T2->Right);
    
    else//如果两棵树左子树(一个空一个不空或者都不空)并且数据不一样,那么判断第一棵树的左(右)儿子是否跟第二棵树的右(左)儿子同构
         return Isomorphic(T1->Left,T2->Right)&&Isomorphic(T1->Right,T2->Left);

}

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
判断两个二叉树是否同构可以使用递归和分治法思想,下面是两种实现方式: 1. 递归实现 递归实现的思路是分别判断两个二叉树的左子树和右子树是否同构,如果左右子树都同构,则判断两个二叉树的根节点是否相同。代码如下: ```python def is_isomorphic(root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return False return (is_isomorphic(root1.left, root2.left) and is_isomorphic(root1.right, root2.right)) or \ (is_isomorphic(root1.left, root2.right) and is_isomorphic(root1.right, root2.left)) ``` 2. 分治实现 分治实现的思路是将两个二叉树分别划分成左子树和右子树,然后递归判断左子树和右子树是否同构,最后判断两个二叉树的根节点是否相同。代码如下: ```python def is_isomorphic(root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return False return (is_isomorphic(root1.left, root2.left) and is_isomorphic(root1.right, root2.right)) or \ (is_isomorphic(root1.left, root2.right) and is_isomorphic(root1.right, root2.left)) def is_isomorphic_dc(root1, root2): if not root1 and not root2: return True if not root1 or not root2: return False if root1.val != root2.val: return False return is_isomorphic_dc(root1.left, root2.left) and \ is_isomorphic_dc(root1.right, root2.right) and \ is_isomorphic_dc(root1.left, root2.right) and \ is_isomorphic_dc(root1.right, root2.left) ``` 以上两种方法都可以判断两个二叉树是否同构,其中递归实现的代码比较简洁,分治实现的代码稍微复杂一些,但是思路清晰。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值