我正在用 Java 实现一个 N-ary 树;每个节点可以有尽可能多的节点。当我尝试构建一棵树时,问题就来了。我有一个函数可以递归地创建一个特定高度的树,并根据节点列表分配子节点。当我调用该函数时,根节点不包含任何数据;一旦完成,它就会返回一个空值。我从未实现过 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;
}
非常感谢任何帮助!