Vergelijk bomen met behulp van heiligverklaring aanpak door gesuggereerd @mcdowella . Het verschil is dat mijn aanpak niet nodig O(N)extra geheugen mbt aantal knooppunten in de boom:
# in Python
from collections import namedtuple
from itertools import chain
# Tree is either None or a tuple of its value and left, right trees
Tree = namedtuple('Tree', 'value left right')
def canonorder(a, b):
"""Sort nodes a, b by their values.
`None` goes to the left
"""
if (a and b and a.value > b.value) or b is None:
a, b = b, a # swap
return a, b
def canonwalk(tree, canonorder=canonorder):
"""Yield all tree nodes in a canonical order.
Bottom-up, smaller children first, None is the smallest
"""
if tree is not None:
children = tree[1:]
if all(t is None for t in children): return # cut None leaves
children = canonorder(*children)
for child in chain(*map(canonwalk, children)):
yield child
yield tree
canonwalk()vereist O(N*M)stappen en O(log(N)*M)geheugen om alle knooppunten op in een boom, waarbij Nis totale aantal knooppunten, Maantal kinderen ieder knooppunt (het 2 binaire bomen).
canonorder()kan gemakkelijk worden gegeneraliseerd voor knooppunt representatie en elk aantal kinderen. canonwalk()vereist slechts dat een boom als een opeenvolging hebt toegang tot de directe kinderen.
De vergelijking functie die roept canonwalk():
from itertools import imap, izip_longest
unset = object()
def cmptree(*trees):
unequal = False # allow root nodes to be unequal
# traverse in parallel all trees under comparison
for nodes in izip_longest(*imap(canonwalk, trees), fillvalue=unset):
if unequal:
return False # children nodes are not equal
if any(t is unset for t in nodes):
return False # different number of nodes
if all(t is not None for t in nodes):
unequal = any(nodes[-1].value != t.value for t in nodes)
else: # some are None
unequal = any(t is not None for t in nodes)
return True # equal
Voorbeeld
5 6
/ \ / \ they are equal.
1 2 2 1
/ \ / /
3 4 4 3
tree1 = Tree(5,
Tree(1,
Tree(3, None,None), None),
Tree(2,
None, Tree(4, None, None)))
tree2 = Tree(6,
Tree(2, Tree(4, None, None), None),
Tree(1, Tree(3, None, None), None))
print cmptree(tree1, tree2)
uitgang
True