Java algorithm for comparing subtree trees

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

Tree1

Tree2

enter image description here

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;

        // check all subtrees of Tree1
        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;
}

, , . , ?

+4
1

Aight, . , , , . , , , " " , .

. , .

( ), node P node T , P node T. , : , P , ? node T, !

: , , , , , , . , .

, . ,

  • , .
    • , D, , ( !) .
  • , - height-1 .
    • , -1 node Q , X Y.
    • , X Y. , ( , X Y)
    • , - X , Y .
    • , ! - , Q, ! - .
  • height-1 , , height-1 .
  • , 2, -1.
  • , -3 dic- . , .

, , Googling ( , / ). - , . , , , , , .

+3

All Articles