我正在用Java实现一个N-ary树;每个节点可以拥有尽可能多的节点 . 当我尝试构建一棵树时,问题出现了 . 我有一个递归创建特定高度的树的函数,并根据节点列表分配子节点 . 当我调用该函数时,根节点不包含任何数据;它完成后返回null . 我从来没有实现过N-ary树,所以我对实现有点肯定,任何关于它的指针都会非常感激!
//Creates a tree
void createTree(int height) throws InvalidMoveException,
Modified_Tree.InvalidMoveException {
root = new ListNode();
root = populateTree(moves.root,height,true,0);
}
//Function called by Create tree to populate the tree
//It takes in a ListNode, an int height that determines the height of the tree,
//and a boolean, which is used
//To know whether the node is a black piece/max or a white piece/min
public ListNode populateTree(ListNode root, int height, boolean black, int score)
{
ListNode node = root;
List<ListNode> nodes = new List<ListNode>(10);
//Sets the size of List in node to the int taken
node.setChildNumber(nodes.size());
//return if reached the pre-maximum height
if(height == 1){
for(int i = 0; i < nodes.size(); i++){
//Add the child to the last node
node.addChild(nodes.get(i));
}
return node;
}
else{
for(int j =0; j < node.getChildNumber(); j++){
node = populateTree(node.getChildAt(j),height-1,!black,score);
}
}
return node;
}
任何帮助真的很感激!
1 回答
你的问题在这里:
首先,我假设您的意思是
new ArrayList<ListNode>(10);
或List<T>
的其他一些具体实现 . 其次,参数10
仅确保您最初将拥有10
个位置 . 这并不意味着您将在nodes
内自动初始化10
ListNode
个实例 . 然后你有:此循环将永远不会执行,因为
nodes.size()
为零,因为它根本不包含任何节点 . 因此,您需要首先使用ListNode
实例初始化列表 .