title: Find all subtrees in a tree matching a given subtree in Java
body: <p>I am writing code in Java that uses an unordered, rooted tree where each node may have any number of child nodes. Given a tree T and a subtree S, I want to be able to find all the subtrees in T that match S (that is all the subtrees in T that are isomorphic to S).</p>
  
  <p>A subtree of T is isomorphic to S, if the nodes of S can be mapped to nodes of T in such a way that the edges of S map to edges in T.</p>
  
  <p>A <a href="https://stackoverflow.com/questions/584696/easy-way-to-find-subtree-in-a-tree">previous question</a> has been asked on how to find if a tree contains another subtree however I want to be able to find <b>ALL</b> subtrees in T that match S. In addition I want to be able to map from each node in each match in T to the corresponding node in S. </p>
  
  <p>That is, when a match is found, it should be returned not simply as a pointer to the node in T where a tree is rooted that matches S, but the match should be returned as something like a list of pairs of pointers to nodes [(T1,S1),(T2,S2),...(Tn,Sn)] such that T1 is a pointer to a node in T that maps to node S1 in the subtree and so on. </p>
  
  <p>Alternatively simply a list of pairs of values could be returned as each node in tree T and subtree S has a unique integer identifier associated with it.</p>
  
  <p>For example:</p>
  
  <p>Given tree T as follows:</p>
  
  <pre><code>    a
     / \
    b   c
   / \  
  d   e
  </code></pre>
  
  <p>and subtree S as:</p>
  
  <pre><code>    x
     / \
    y   z
  </code></pre>
  
  <p>the following list of matches should be returned:</p>
  
  <blockquote>
    <p>[(a,x),(b,y),(c,z)]
    [(b,x),(d,y),(e,z)]</p>
  </blockquote>
  
  <p>A unique match is determined by the set of nodes in T, <b>not</b> the mapping between the nodes in T and S. </p>
  
  <p>So the following match:</p>
  
  <blockquote>
    <p>[(a,x),(b,<b>z</b>),(c,<b>y</b>)]</p>
  </blockquote>
  
  <p>is considered to be duplicate of </p>
  
  <blockquote>
    <p>[(a,x),(b,<strong>y</strong>),(c,<strong>z</strong>)]</p>
  </blockquote>
  
  <p>because they have the same set of nodes from T (a,b,c) so only one of the matches should be returned.</p>
  
  <p>As another example, given tree T:</p>
  
  <pre><code>    a
     /|\
    b c d
  </code></pre>
  
  <p>and subtree S:</p>
  
  <pre><code>  x
   / \  
  y   z
  </code></pre>
  
  <p>the following list of matches should be returned:</p>
  
  <blockquote>
    <p>[(a,x),(b,y),(c,z)]
    [(a,x),(b,y),(d,z)]
    [(a,x),(c,y),(d,z)]</p>
  </blockquote>
  
  <p>Can anyone give any example code of how to do this?</p>
  
  <p><strong>Edit (in relation to Chris Kannon's comment):</strong>   </p>
  
  <blockquote>
    <p>I'm thinking you want someone to code
    the answer for you? How far have you
    gotten? What code have you written? –
    Chris Kannon 1 hour ago</p>
  </blockquote>
  
  <p>I have the following code which when run, builds up a list (matchesList) of pointers to nodes in the tree where subtrees are rooted that match the given subtree. However there may be multiple subtrees rooted at the same node and currently each node will only be added at most once to matchesList regardless of how many matches are rooted there. </p>
  
  <p>In addition, I cannot work out how to build up the mapping described above between nodes in the subtree and nodes in the match found in the original tree.</p>
  
  <pre><code>package Example;
  
  import java.util.LinkedList;
  import java.util.Vector;
  
  public class PartialTreeMatch {
      public static void main(String[] args) {
          NodeX testTree = createTestTree();
          NodeX searchTree = createSearchTree();
  
          System.out.println(testTree);
          System.out.println(searchTree);
  
          partialMatch(testTree, searchTree);
      }
  
      static LinkedList&lt;NodeX&gt; matchesList = new LinkedList&lt;NodeX&gt;();
  
      private static boolean partialMatch(NodeX tree, NodeX searchTree) {
          findSubTreeInTree(tree, searchTree);
          System.out.println(matchesList.size());
          for (NodeX n : matchesList) {
              if (n != null) {
                  System.out.println("Found: " + n);
              }
          }
  
          return false;
      }
  
      private static NodeX findSubTreeInTree(NodeX tree, NodeX node) {
          if (tree.value == node.value) {
              if (matchChildren(tree, node)) {
                  matchesList.add(tree);
  
              }
          }
  
          NodeX result = null;
          for (NodeX child : tree.children) {
              result = findSubTreeInTree(child, node);
  
              if (result != null) {
                  if (matchChildren(tree, result)) {
                      matchesList.add(result);
  
                  }
              }
          }
  
          return result;
      }
  
      private static boolean matchChildren(NodeX tree, NodeX searchTree) {
          if (tree.value != searchTree.value) {
              return false;
          }
  
          if (tree.children.size() &lt; searchTree.children.size()) {
              return false;
          }
  
          boolean result = true;
          int treeChildrenIndex = 0;
  
          for (int searchChildrenIndex = 0; searchChildrenIndex &lt; searchTree.children
                  .size(); searchChildrenIndex++) {
  
              // Skip non-matching children in the tree.
              while (treeChildrenIndex &lt; tree.children.size()
                      &amp;&amp; !(result = matchChildren(tree.children
                              .get(treeChildrenIndex), searchTree.children
                              .get(searchChildrenIndex)))) {
                  treeChildrenIndex++;
              }
  
              if (!result) {
                  return result;
              }
          }
  
          return result;
      }
  
      private static NodeX createTestTree() {
  
          NodeX subTree2 = new NodeX('A');
          subTree2.children.add(new NodeX('A'));
          subTree2.children.add(new NodeX('A'));
  
          NodeX subTree = new NodeX('A');
          subTree.children.add(new NodeX('A'));
          subTree.children.add(new NodeX('A'));
          subTree.children.add(subTree2);
  
          return subTree;
      }
  
      private static NodeX createSearchTree() {
          NodeX root = new NodeX('A');
          root.children.add(new NodeX('A'));
          root.children.add(new NodeX('A'));
  
          return root;
      }
  }
  
  class NodeX {
      char value;
      Vector&lt;NodeX&gt; children;
  
      public NodeX(char val) {
          value = val;
          children = new Vector&lt;NodeX&gt;();
      }
  
      public String toString() {
          StringBuilder sb = new StringBuilder();
  
          sb.append('(');
          sb.append(value);
  
          for (NodeX child : children) {
              sb.append(' ');
              sb.append(child.toString());
          }
  
          sb.append(')');
  
          return sb.toString();
      }
  }
  </code></pre>
  
  <p>The code above tries to find all the subgraphs in:</p>
  
  <pre><code>  A
   /|\  
  A A A
     / \
    A   A
  </code></pre>
  
  <p>which match:</p>
  
  <pre><code>    A
     / \
    A   A
  </code></pre>
  
  <p>The code successfully detects that there is a match rooted an the top node in first tree and the 3rd child of the first tree. However, there are actually 3 matches rooted at the top node, not just one. In addition, the code does not build up a mapping between nodes in the tree and nodes in the subtree and I cannot work out how to do this.</p>
  
  <p>Can anyone offer any advice on how to do this?</p>