我正在实现一棵基于 this 的树回答。根据给定的简单用法示例,新节点以乳清在树中的位置命名,因此它们是变量。 例如:
TreeNode<String> node0 = root.addChild("node0");
其中node0是一个新的TreeNode以及新子节点将拥有的数据。
我打算为我的树的每个节点创建 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
}
}
还是我缺少更好的解决方案?谢谢
最佳答案
首先,我将每个节点的“名称”存储在一个成员变量中,并为其定义一个 getter。我还会添加一个方法来获取节点已有的子节点数量。如果这样做,您将在实例化节点时自动命名它们。在类定义中添加:
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;
}
我希望这会有所帮助。
关于java - 命名树结构的节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35530543/