I’m writing some code that uses a Tree (a regular tree that can have an unlimited number of nodes, but no crossover, i.e. two parent nodes will not point the the same child node). Anyway, two things:
1) Are there any well-known algorithms for finding a sub-tree within a tree.
2) Are there any Java libraries (or any libraries for that matter) that already implement this algorithm? Even if there are none, can anyone recommend any good general purpose Java tree library?
I want to use these trees for holding data in a tree format, not for their searching capabilities.
To expand a bit: I’m using the tree as part of game to keep a history of what happens when a certain events happen. For example, an A can hit a B which can hit two A’s which can hit another two A’s etc.
That would look something like:
A | B / A / \ A A / \ A A
Of course there’s more than just A and B. What I want to do is (for an achievement system) is be able to tell when, say an A has hit two A’s:
A / \ A A
I want to be able to easily know if the first tree contains that subtree. And I don’t want to have to write all the code for doing so if I don’t have to 🙂
Looks like a straightforward algorithm: Find the root of the search tree in the game tree and check whether the children of the search tree are a subset of the children in the game tree.
From your explanations, I’m not sure whether the search tree
should match this tree:
(i.e. if non-matching children are supposed to be ignored.)
Anyway, here’s the code I just toyed around with. It’s a fully running example and comes with a main method and a simple
Nodeclass. Feel free to play with it: