Tree Traversal in Java using Visitor pattern and For loop Example Codes
Java Oracle |
Writing codes in Java is supposed to be reusable, it means that your code can be reused by yourself and other people working on similar things you do without rewriting the same code block over and over.
This is an example of object oriented passion on how you can use an object that could possibly have infinite children. You can use this class so you don’t need to write a loop over and over.
Firstable given data person with children and grandchildren below.
Now we can use for loop and visitor pattern to visit all the children recursively.
1. For loop
The first example is a usual, easy to understand Example of how you write a Recursive method to visit tree traversal children using for loop.
Using for loop is really really simple but Somewhat looks not an elegant way, and it could lead into bugs if you misplace variables before and after calling the recursive method. When the code gets bigger it becomes a mess.
2. Visitor Pattern
And here’s the Object oriented way, using a Visitor pattern.
Believe me it’s much more OOP way and if you are using an advanced IDE, it can easily provide you with a code assistant on how to do tree traversal works.
You can read more detail about the Visitor pattern in this wikipedia article (https://en.wikipedia.org/wiki/Visitor_pattern).
If you noticed @Data annotation, it is from library Lombok, it’s a cool java library for simplifying a class Object so you don’t need to create getter and setter manually.
Code available at github mudiadamz/techgalery.