I am looking for an algorithm to compare two trees with each other and check if the tree on is a subtree of the other.
First, I introduced my own implementation of the tree, which has the following structure:
public class PlatformTree {
private HwNode root;
.......
}
public class HwNode {
private HwNode parent;
private ElementType elementType;
private Hardware hw;
private List<Node> children = new ArrayList<Node>();
public Node(Node parent, ElementType elementType, Hardware hw) {
...
}
public void addChild(Node child) {
children.add(child);
}
....
The following images should give you an overview:
Tree1

Tree2

As shown in the image, I want to check if all subtrees of Tree1 are contained in Tree2. The root elements of trees are just dummy elements that are used to access subtrees.
I always check if Tree2 contains subtrees of Tree1. Nodes of type Tree1 always have one successor (Microcontroller.Memory), and nodes of type Tree2 can have several successors (Microcontroller.Memory / Memory / Memory).
ElementType determines whether Nodes are equal or not.
True, . False. , , . , :
TreePlatform:
public boolean containsSubTree(PlatformTree tree1) {
Boolean b = true;
if (tree1.getRoot() != null && getRoot() != null) {
for (HwNode subRootNode : tree1.getRoot().getChildren()) {
b = getRoot().containsSubTree(subRootNode);
}
} else {
return false;
}
return b;
}
HwNode
public boolean containsSubTree(HwNode abstractNode) {
for (HwNode subRootNode : getChildren()) {
if (hasSubTree(subRootNode, abstractNode)) {
return true;
}
}
return false;
}
private boolean hasSubTree(HwNode subRootNode, HwNode abstractNode) {
if (subRootNode.getElementType() != abstractNode.getElementType()) {
return false;
}
if (!abstractNode.getChildren().isEmpty()) {
if (!subRootNode.getChildren().isEmpty()) {
HwNode abstractSubNode = abstractNode.getChildren().get(0);
for (HwNode subNode : subRootNode.getChildren()) {
if (!hasSubTree(subNode, abstractSubNode)) {
return false;
}
}
} else {
return false;
}
} else if (subRootNode.getChildren().isEmpty()) {
return true;
}
return true;
}
, , . , ?