Tree Canonization Simplified

While debugging the methods to make canonical signatures, I learned something about tree isomorphism from various sources, including Prof. Valiente's excellent looking book on trees.

One way of checking isomorphism is canonisation, since two trees are only isomorphic if they have the same canonical form. For simple labelled trees, it looks like there is an almost trivial way to get a canonical string representation. Say we have two trees:


The are rooted, labelled trees. So the conversion to a canonised string proceeds as follows; for each node, lexicographically sort the string form of the labels of its children, and return the concatenated string. In python this looks like:



which...is unreadable. hmmm. Wish there was a better way to get marked-up code into blog posts. Perhaps there is one, and I don't know of it. Anyway, the point is that it is very short.

edit : the code is...


def printSorted(node):
if len(node.children) > 0:
childStrings = [printSorted(child) for child in node.children]
return node.label + "("+ "".join(sorted(childStrings)) + ")"
else:
return node.label

Comments

Rich Apodaca said…
Simple and clear. I wonder how can you use this to develop a graph canonicalization algorithm?

For displaying source, you might also check out Gist:

http://gist.github.com/

Or maybe this:

http://stackoverflow.com/questions/687213/what-websites-do-you-use-to-post-temporary-code-snippets
gilleain said…
Egon : Thanks - I think I saw that before, but never went to the trouble of finding out how to use it in blogspot. This post was helpful:

http://manuelmoeg.blogspot.com/2009/03/def-hello-pass.html

although it's a bit odd that google themselves have not integrated a prettifier.
gilleain said…
Rich : From what I have read (and from what I have understood from that) I don't know if this is possible.

I should point out that the method I describe is not my own, but a simplified version of that described by Tarjan and Hopcroft in a paper on, well, graph isomorphism.

Their method only works for planar graphs, and is fiendishly complex - there are at least two papers that were written to explain the algorithm!

In any case, the lexicographically-sorted canonical string form of the labelled tree does not work for signatures in general. Signatures can represent cycles using tree nodes that are numbered - as with smiles notation where you have C1CCCC1 for a 5-membered ring.