[英]Creating a tree data structure in java?
I am trying to create a tree data structure in java where each parent node can have only three child nodes but I'm stuck on adding a node to the tree in the case where a node has at least one child but less than 3 child nodes. 我试图在Java中创建一个树数据结构,其中每个父节点只能有三个子节点,但是如果一个节点至少有一个子节点但少于3个子节点,则我会坚持将一个节点添加到树中。 I'm unsure if I should use a Iterator to iterator through the list of nodes for the current node I'm on.
我不确定是否应该使用Iterator来迭代当前所在节点的节点列表。 I tryed to use a variable that would increment each time the
add()
method was called. 我尝试使用一个变量,该变量在每次调用
add()
方法时都会增加。 here's my code: Node class: 这是我的代码:节点类:
public class Node {
int keyValue;
int nodeLabel;
ArrayList<Node> nodeChildren;
private static int count;
Node(int _keyValue)
{
this.nodeLabel = count;
this.keyValue = _keyValue;
this.count++;
nodeChildren = new ArrayList<Node>();
}
public String toString()
{
return "Node " + nodeLabel + " has the key " + keyValue;
}
}
Tree class: add()
method 树类:
add()
方法
Node rootNode;
int incrementor = 0;
public void addNode(int nodeKey)
{
Node newNode = new Node(nodeKey);
if (rootNode == null)
{
rootNode = newNode;
}
else if (rootNode.nodeChildren.isEmpty())
{
rootNode.nodeChildren.add(newNode);
}
else if (!rootNode.nodeChildren.isEmpty())
{
Node currentNode = rootNode;
Node parentNode;
incrementor = 0;
while (currentNode.nodeChildren.size() < 3)
{
//currentNode.nodeChildren.add(newNode);
if (currentNode.nodeChildren.size() == 3)
{
parentNode = currentNode.nodeChildren.get(incrementor);
currentNode = parentNode;
currentNode.nodeChildren.get(incrementor).nodeChildren.add(newNode);
}
else
{
parentNode = currentNode;
currentNode = currentNode.nodeChildren.iterator().next();
currentNode.nodeChildren.add(newNode);
}
incrementor = incrementor + 1;
}
System.out.println(rootNode.nodeChildren.size());
}
}
I get a IndexOutOfBounds exception when a third node is added to tree 将第三个节点添加到树时,出现IndexOutOfBounds异常
while (currentNode.nodeChildren.size() < 3)
will cause 会引发
if (currentNode.nodeChildren.size() == 3)
to always evaluate to false, thus the parent node will never switch to a child. 总是评估为false,因此父节点永远不会切换到子节点。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.