什么是同构树
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.
简单来说,对于二叉树,如果一个树的孩子节点通过左右变换可以变成另外一个树,那么这两个树是同构的。举个栗子
将上图左边树中的 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