Graph Theory – Finding a Subtree in a Tree

graphtrees

I have a tree:

    a
   / \
  b   c
 / \
d   f
   / \ 
  g   h

And the pattern:

    x
   / \
  y   z
 / \
q   p

As output I would like to have:

x: a
y: b
z: c
q: d
p: f

and

x: b
y: f
z: c
q: g
p: h

Is there any algorithm I could look at?

Best Answer

  1. Flatten your pattern into a breadth-first array of tuples including the node name, depth, and index, like:

    (a,0,0), (b,1,0), (c,1,1), (d,2,0)...

  2. Traverse (or flatten) your input tree in breadth-first order, ideally using the same method.
  3. The n-th item in your pattern array will match the n-th item in the input tree, assuming there is one. You can use the depth and index values of each tuple to skip ahead until something matches.
There are really good breadth-first traversal code samples all over the place, it should be easy to find one in the language of your choice.

Related Topic