title: Creating a tree data structure in java?
body: <p>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 <code>add()</code> method was called. 
  here's my code:
  Node class:</p>
  
  <pre><code>public class Node {
  
      int keyValue;
      int nodeLabel;
      ArrayList&lt;Node&gt; nodeChildren;
  
      private static int count;
  
      Node(int _keyValue)
      {
          this.nodeLabel = count;
          this.keyValue = _keyValue;
          this.count++;
          nodeChildren = new ArrayList&lt;Node&gt;();
      }
  
      public String toString()
      {
          return "Node " + nodeLabel + " has the key " + keyValue;
      }
  
  }
  </code></pre>
  
  <p>Tree class: <code>add()</code> method</p>
  
  <pre><code>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() &lt; 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());
          }
      }
  </code></pre>
  
  <p>I get a IndexOutOfBounds exception when a third node is added to tree</p>