Skip to content
Advertisement

How to tidying my Java code because it has too many looping [closed]

I have a Node class used to represent a tree structure. Within this class, I’ve defined a print method that should yield the following output:

JavaScript

This is how I’ve written my print method:

JavaScript

This is also the Node class implementation to better help you in understanding the scenario:

JavaScript

I think my code is quite dirty and can be improved. I’d like to define a recursive method but I still don’t understand how recursion works. Could someone help me with that?

Advertisement

Answer

To define a recursive method, you first need to identify your base cases and recursive cases. In this scenario, the base case is when the node passed for the printing is null while the recursive case is when there are still children to be printed.

Since I understand that your program might be a school exercise, I’ll avoid discussing what could be or could be not a better implementation of your Node class. Definitely, using a List data structure from the Collections framework would have been a better choice instead of a fixed array of 100 elements, but I think your teacher would like to keep things simple at the beginning and you most likely haven’t covered the Collections framework yet since you said you’re still struggling with recursion (which is totally fine, we all have to start somewhere!). So, I’ll leave your class implementation exactly how it is. I will just add few methods and some tweaks.

Here, I’ve implemented a solution to show you how your recursive print could work. Bear in mind that I’ve split the print implementation in two methods only to make its invocation easier for the client. In fact, a client should not be aware nor bothered with the internal implementation details of something to make it work.

JavaScript

Here I just wanted to add a couple of side notes:

  • children is already the plural form of child. You don’t need to call your array childrens.

  • Your previous implementation of the add method could have raised an ArraIndexOutOfBoundsException, if you had added more than 100 elements. Usually, when an operation could fail, the method should return a boolean to tell the client whether the operation succeeded or not.

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