有什么方法可以有效地比较treelib中的两棵树吗?
如果2个树的相同,则返回true
通过相同,匹配的节点应该具有相同的标签,并且两个树中每个匹配节点之间的父子关系是相同的
from treelib import Node, Tree
def compare_trees(node1, node2):
# reimplement this comparison based on your needs: use data,...
if(node1.tag != node2.tag):
return False
else:
# access global trees
children1 = tree1.children(node1.identifier)
children2 = tree2.children(node2.identifier)
if len(children1) != len(children2):
return False
elif len(children1) > 0:
# recusivly compare children
return all([compare_trees(c1i, c2i) for c1i, c2i in zip(children1, children2)])
else:
return True
tree1 = Tree()
tree1.create_node("Harry", "harry") # root node
tree1.create_node("Jane", "jane", parent="harry")
tree1.create_node("Bill", "bill", parent="harry")
tree2 = Tree()
tree2.create_node("Harry", "harry") # root node
tree2.create_node("Jane", "jane", parent="harry")
tree2.create_node("Bill", "bill", parent="harry")
compare_trees(tree1.get_node(tree1.root), tree2.get_node(tree2.root))