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
Tree data structure is useful on occasions where linear representation of data do not suffice, such as creating a family tree. Java provides two in-built classes, TreeSet and TreeMap, in Java Collection Framework that cater to the needs of the programmer to describe data elements in the aforesaid form.
Insert Operation The very first insertion creates the tree. Afterwards, whenever an element is to be inserted, first locate its proper location. Start searching from the root node, then if the data is less than the key value, search for the empty location in the left subtree and insert the data.
In Java, a tree node is implemented using a class. The data inside every node can be a string, char, integer, double, or float data type. A binary tree can be implemented in two ways: A node representation and an array representation.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With