我正在尝试在Java中创建一种树形数据结构,其中每个父节点只能有三个子节点,但是当一个节点至少有一个子节点但少于3个子节点时,在向树中添加节点方面我卡住了。我不确定是否应该使用迭代器来遍历当前节点的节点列表。我试图使用一个变量来递增,每次调用add()
方法时都会增加。
以下是我的代码:
Node类:
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;
}
}
树类: 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());
}
}
当第三个节点添加到树中时,我会收到一个IndexOutOfBounds异常。