tree matching algorithm

Let's talk about algorithms!

Moderator: Board moderators

Post Reply
coolbila
New poster
Posts: 8
Joined: Tue Apr 01, 2003 8:11 pm

tree matching algorithm

Post by coolbila »

I meet a tree matching problem.

Does any one know how to compare whether two trees are the same or not ?
Oh my God ... Wrong Answer
Cosmin.ro
Learning poster
Posts: 95
Joined: Thu Aug 21, 2003 12:02 am

Post by Cosmin.ro »

You need to represent the trees as a sequence of paratnhesis, for example:

Code: Select all

    1
  / | \   (()()())
 2  3  4

    1
    |
    2   ((()))
    |
    3

    1
    |
    2   ((()()))
   / \
  3   4    
Basicly what you do is dfs and write a open parantesis when you go down a edge and a closed parantesis when you go up a edge.
Now you have to make the code cannonical, this means that for example the folowing two expressions ((())()) and (()(())) represent two isomorphic trees.
To get a connonical code for a tree you must first get the cannonical codes of the subtrees and sort them lexicographically and concatenate them and put at the beginning a open parantesis and at the end a closed parantesis. (in the example above (()) < () lexicographically so the canonical representation is ((())()).)
Now what I said applies to rooted trees, but if trees have no root and you have to check if they are isomorphic than you could fix a node in the first tree as the root of the first tree and try for the second tree every node as a root, or you can do it faster by knowing the fact that every tree has one or two centers and you first find the centers of the two trees and consider them roots and then get the cannonical code of the trees.
coolbila
New poster
Posts: 8
Joined: Tue Apr 01, 2003 8:11 pm

Post by coolbila »

Thank you very much
This answer is very useful for me. :lol:
Oh my God ... Wrong Answer
Pavl0
New poster
Posts: 16
Joined: Sun Apr 18, 2004 2:57 pm

Post by Pavl0 »

in what problem this algo can be used ??
Post Reply

Return to “Algorithms”