Creating a tree data structure in java?

user2152012 picture user2152012 · Dec 3, 2013 · Viewed 10.9k times · Source

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 add() method was called. here's my code: Node class:

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

}

Tree class: add() method

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());
        }
    }

I get a IndexOutOfBounds exception when a third node is added to tree

Answer

C.B. picture C.B. · Dec 3, 2013
while (currentNode.nodeChildren.size() < 3)

will cause

if (currentNode.nodeChildren.size() == 3)

to always evaluate to false, thus the parent node will never switch to a child.