Isomorphic 同构树(图)的实现

什么是同构树

Two trees are called isomorphic if one of them can be obtained from other by a series of flips, i.e. by swapping left and right children of a number of nodes. Any number of nodes at any level can have their children swapped. Two empty trees are isomorphic.

简单来说,对于二叉树,如果一个树的孩子节点通过左右变换可以变成另外一个树,那么这两个树是同构的。举个栗子isomorphic trees
将上图左边树中的 2和3,6和null,7和8左右对换后,就变成了右边的树。

那么我们可以得出:第一,同构树的节点数要相同;第二,同构树节点内的数据要相同。

代码实现

那么怎么用算法判断两个树是否同构呢?我们以python为例。

class Node: 
    #二叉树构造函数
    def __init__(self, data): 
        self.data = data 
        self.left = None
        self.right = None
      
#判断两个树是否为同构
def isIsomorphic(n1, n2): 
      
    #如果两个树都为空
    if n1 is None and n2 is None: 
        return True
  
    #如果只有一个树为空
    if n1 is None or n2 is None: 
        return False
        
  	#如果节点内的数据不一致
    if n1.data != n2.data : 
        return False
        
    # 两棵同构树要么左节点=左节点,要么左节点=右节点
    return ((isIsomorphic(n1.left, n2.left)and 
            isIsomorphic(n1.right, n2.right)) or
            (isIsomorphic(n1.left, n2.right) and 
            isIsomorphic(n1.right, n2.left)) 
            )

n1 = Node(1)
n1.left = Node(2)
n1.right = Node(3)

n2 = Node(1)
n2.left = Node(3)
n2.right = Node(2)

print(isIsomorphic(n1, n2)) #True
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值