如何将树合并在一起,其中一棵树的根等于另一棵树的根?

How to merge Trees together where the root of one tree equals the root of a other tree?

我目前正在尝试实现树(不是二进制,顺序无关紧要,not-directed)数据结构。 当一棵树的根与另一棵树的 children 节点相同时,我想将树合并在一起。
第一棵树的 children 应该变成第二棵树 children 的 children ,这与第一棵树的根相同。 要合并的树可以更深。

例如(编号为顶点的identifier/Names):

我这样实现了 TreeNode.java

public class TreeNode {
    private TreeNode parent;
    private List<TreeNode> children;
    private IP vertexName;
    private int height;
    
    //This creates the root vertex, of the Tree.
    public TreeNode(IP vertexName) {
        this.vertexName = vertexName;
        this.parent = null;
        this.height = 0;
        this.children = new ArrayList<>();
    }
    
    //This is for creating other members of a tree besides the root, the children vertices.
    public TreeNode(TreeNode parentTreeNode, IP vertexName) {
        this.children = new ArrayList<>();
        this.parent = parentTreeNode;
        this.height = (parentTreeNode.getHeight() + 1);
        this.vertexName = vertexName;
        parentTreeNode.children.add(this);
    }


    public void addChildren(List<IP> verteciesIPs) throws NotATreeException {
        areValidChildren(verteciesIPs);

        for (IP ip:verteciesIPs) {
            TreeNode treeNode = new TreeNode(ip);
            treeNode.setParent(this);
            treeNode.setHeight(this.getHeight() + 1);
            this.children.add(treeNode);
        }
    }

    public void addChild(TreeNode treeNodeChildren) {
        treeNodeChildren.setParent(this);
        treeNodeChildren.setHeight(this.getHeight() + 1);
        this.children.add(treeNodeChildren);
    }

    public void areValidChildren(final List<IP> verteciesIPs) throws NotATreeException {
        if (hasDuplicateChildren(verteciesIPs)) {
            throw new NotATreeException("Duplicate entries");
        }

然后我有一个树列表List<TreeNode> treeTopology我想合并在一起。 但我不太确定该怎么做,因为我不仅需要检查 children 节点是否与给定树的根节点相同。
还有 children children 等等。

我希望有人能帮助我。

为了简单起见,我没有 post 整个代码。

我尝试用两个 for-loops 和另一个 for-loop 迭代 List<TreeNode> treeTopology 来迭代 children。但这种方法似乎不太奏效。因为我只能比较 children 并且每个 children 的 children.

都需要一个循环

您可以实现一个函数来检查树 contains() 是否为给定的数字,然后您可以在每次要添加新值时调用该函数。 ifcontains() 数字 continue 否则将数字添加为要添加到的节点的子节点。您可以尝试查看 DFS 或 BFS,因为您的树更像是一个图形而不是实际的树。