简体   繁体   中英

Populating an N-ary Tree- Java

I'm implementing a N-ary tree in Java; each node can have as many nodes as possible. The problem comes when I try to build a tree. I have a function that recursively creates a tree of a specific height, and assigns the child nodes based from a List of Nodes. When I call the function the root node dose not contain any data; it returns a null once it is finished. I have never implemented an N-ary tree so I'm somewhat sure of the implementation, any pointers on it would really be appreciated!

//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;
 }

Any help is really appreciated!

Your problem is here:

List<ListNode> nodes = new List<ListNode>(10);

First, I assume you meant new ArrayList<ListNode>(10); or some other concrete implementation of List<T> . Second, the argument 10 only ensures that you will have 10 locations initially. It does not mean that you will have 10 ListNode instances automatically initialized inside nodes . Then you have:

    for(int i = 0; i < nodes.size(); i++){
        //Add the child to the last node
        node.addChild(nodes.get(i));
    }

This loop will never execute because nodes.size() is zero due to it not containing any nodes at all. So you need to initialized your list with ListNode instances first.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM