命名树结构的节点

Naming the nodes of a Tree Structure

我正在根据 this 答案实现一棵树。根据给定的简单用法示例,新节点以乳清在树中的位置命名,因此它们是变量。 例如:

TreeNode<String> node0 = root.addChild("node0");

其中 node0 是一个新的 TreeNode 和新子节点将拥有的 data

根据this and this,我不能使用字符串来命名变量。

我打算为我的树的每个节点创建 26 个子节点。我的问题很简单,我是否必须通过手动创建我的树将具有的所有 26 个可能节点来创建树,如下所示?

TreeNode<String> node0 = root.addChild("node0");
TreeNode<String> node1 = root.addChild("node1");
TreeNode<String> node2 = root.addChild("node2");
...
TreeNode<String> node25 = root.addChild("node25");
{
    TreeNode<String> node00 = node0.addChild("node00");
    ...
    {
        //the above code for all the nodes of the tree
    }
}

还是我缺少更好的解决方案?谢谢

虽然变量名称可能不具有动态性质,但 Map 允许基于具有您设计的命名法的键(即基于树的级别,和它的节点位置)。 这允许在循环中创建节点。

为了便于使用,您可能需要考虑这样的方法:

public String getKeyName(int treeLevel, int nodePosition) {
    // Build the key name...
}

首先,我会将每个节点的"name"存储在一个成员变量中,并为其定义一个getter。我还会添加一个方法来获取节点已有的子节点数。如果这样做,您将在实例化节点时自动命名您的节点。在 class 定义中,添加:

public class TreeNode<T> implements Iterable<TreeNode<T>> {

    T data;
    TreeNode<T> parent;
    List<TreeNode<T>> children;

    ...

    // A string containing the node name, (e.g. "210")
    String name;


    // A name getter method
    public String getName() {
        return this.name;
    }

    // A method to get the number of children that the node has
    public int getNumChildren() {
        return this.children.size();
    }

}

现在,您可以在构造函数中自动命名节点:

public TreeNode<T>(T data, TreeNode<T> parent) {
    ...
    this.parent = parent;
    int numParentChildren = parent.getNumChildren();
    this.name = parent.getName() + numParentChildren;
}

关于你关于创建树的问题,最好封装在一个方法中:

public LinkedList<TreeNode<T>> createTree() {
    //Root TreeNode
    TreeNode<T> root = new TreeNode<T>(data, null);

    //TreeNode on which we currently operate
    TreeNode<T> current;
    //List of treenodes holding the result
    List<TreeNode<T>> treeList = new LinkedList<TreeNode<T>>();
    //Queue holding the nodes for which we will create 26 children elements
    Queue<TreeNode<T>> queue = new LinkedList<TreeNode<T>>();
    treeList.add(root);
    queue.add(root);

    for (int i=0; i< (some number); i++) {
    current = queue.remove();
    child = new TreeNode<T>>(data, current);
    current.addChild(child);
    queue.add(child);
    treelist.add(child);
    }
    return treeList;

}

希望对您有所帮助。