在java中创建树数据结构?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20362913/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Creating a tree data structure in java?
提问by user2152012
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. I'm unsure if I should use a Iterator to iterator through the list of nodes for the current node I'm on. I tryed to use a variable that would increment each time the add()
method was called.
here's my code:
Node class:
我正在尝试在 java 中创建一个树数据结构,其中每个父节点只能有三个子节点,但是在节点至少有一个子节点但少于 3 个子节点的情况下,我坚持向树添加一个节点. 我不确定是否应该使用 Iterator 来遍历我所在的当前节点的节点列表。我尝试使用每次add()
调用该方法时都会增加的变量。这是我的代码:节点类:
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 异常
回答by C.B.
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.
总是评估为假,因此父节点永远不会切换到子节点。