केननिज़ैषण दृष्टिकोण ने सुझाव दिया का उपयोग कर पेड़ की तुलना करें @mcdowella । अंतर यह है कि मेरे दृष्टिकोण की आवश्यकता नहीं है है O(N)पेड़ में एक नोड के अतिरिक्त मेमोरी wrt संख्या:
# 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()आवश्यकता है O(N*M)कदम और O(log(N)*M)एक पेड़ है, जहां में सभी नोड्स उपज के लिए स्मृति Nनोड्स की कुल संख्या है Mबच्चों प्रत्येक नोड है (यह द्विआधारी पेड़ों के लिए 2) की संख्या।
canonorder()आसानी से किसी भी नोड प्रतिनिधित्व और बच्चों के किसी भी संख्या के लिए सामान्यीकृत किया जा सकता है। canonwalk()केवल यह है कि एक पेड़ एक दृश्य के रूप में इसके तत्काल बच्चों को एक्सेस कर सकें।
तुलना समारोह है कि कॉल 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
उदाहरण
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)
उत्पादन
True