在树中添加新的子层

时间:2017-12-12 21:54:46

标签: java tree nodes

我正在制作一张树,并且能够正确设置父母和孩子。在这种情况下,我坚持试图创建一个新的树层,一个孙子。它不是二叉树。理想情况下,我想将新图层的实现放在构造函数或addChild方法中。以下是我设置的内容以及在我的树中设置父母和子女的方法

import java.util.ArrayList;
import java.util.List;

public abstract class TreeNode {

static int count; // store # tree nodes created. Generate IDs

private String id;// unique id # of nodes.

private List<TreeNode> children; // store all children of node

private TreeNode parent; // reference parent of the node. Null is node is root

public TreeNode(List<TreeNode> children) {

    this.children = children;
    this.count++;
    this.id = Integer.toString(this.count);
    int ctr = 0;
    if (children != null) {
        while (ctr < children.size()) {
            children.get(ctr).setParent(this);
            ctr++;
        }
    }
}

public void addChild(TreeNode child) { // add single child to current node

    if (this.getChildren() == null) {
        child.setParent(this);
        this.setChildren(new ArrayList<TreeNode>());
        this.children.add(child);
    }

    else {
        child.setParent(this);
        this.children.add(child);
    }

}

1 个答案:

答案 0 :(得分:0)

为什么班级abstract? (我无法看到扩展它的意图或理由。)

也许我不明白你在问什么;从我所在的位置开始,你已经拥有了“树的新层”的支持 - 实际上你想要多少(至少班级不是abstract)......

TreeNode grandparent = new TreeNode(new ArrayList<TreeNode>());  // I recommend a zero-arg constructor that does this

TreeNode child = new TreeNode(new ArrayList<TreeNode>());
grandparent.addChild(child);

TreeNode grandchild = new TreeNode(new ArrayList<TreeNode>());
child.addChild(grandchild);

您现在拥有一个3级树。

更多建议

您的id字段

id提交的目的是什么?正如您所拥有的那样,您可以在多线程上下文中获得重复项。更好的是......

this.id = UUID.randomUUID().toString();

每个TreeNode都会收到一个唯一的ID(虽然它们不是数字或顺序)。

此外,基于id的{​​{1}}值将是唯一的,即使重新启动VM并且您正在使用持久性UUID对象。

构造函数中的循环

比...更好

TreeNode

会......

while (ctr < children.size()) {
    children.get(ctr).setParent(this);
    ctr++;
}