Skip to content
Advertisement

Parent-Child Tree in Java

I was trying to implement a class Node to build a tree of Nodes. Basically, each Node can have children, so if I specify multiple nodes I can build a tree out of it. As an example:

JavaScript

The problem I am having problems to solve is to build this tree and find all children of a given element (in this case node1 would have 4 children, since it has node2 and node3 in the first place, and node2 has 2 children, so in total 4). Does anyone have any suggestion?

EDIT:

JavaScript

Method where I make use of the class:

JavaScript

CSV file I am getting the data from:

JavaScript

Advertisement

Answer

Here is some sample code that could help (explanation below):

Main class:

JavaScript

Node class:

JavaScript

Output:

JavaScript

Ok so in our node class, let’s say each node will have an integer value, val. That is our first private instance variable. Second, each node will have a list of children nodes, children.

When we first declare our nodes, they will have integer values, as shown in our constructor.

After we define our nodes, we can add some nodes as children to other nodes (v2 and v3 are children to v1, and v4 and v5 are children to v2).

Now we need to print them. We will use a recursive approach for this. If the node we are printing the children of has children (the length of our children ArrayList is nonzero), then we will first iterate through that list, and print out the children of our current node. Afterwards, we again iterate through each child and use the same method (recursion) to print out the children of that node.

I hope this helped! Please let me know if you need any further help or clarification 🙂

EDIT:

Added a getName() method:

JavaScript

Added the requested method:

JavaScript

Quick Explanation: Very similar to the original method, we use a recursive approach to iterate through each nodes’ children: Once we reach a node with no more children, we return null. Once we reach the node with the given value, we return a copy of that node, which will be sent back to wherever the function was called..

Also edited main method:

JavaScript

Output:

JavaScript

SECOND EDIT:

Change the method to look like this:

JavaScript

The main method should look like this:

JavaScript

Output:

JavaScript

THIRD EDIT:

Added a new method:

JavaScript

Edited method:

JavaScript

Main Method:

JavaScript

Output:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement