Tree Traversal Algorithms in Java - OOP
Tree traversal is a very important concept in computer science. Here are three ways to traverse a tree in Java OOP.
The tree data structure that we will be traversing is as shown below:
You first need to represent the tree data structure. We will use a class that will be a template of all the nodes that we will need:
|
|
Next, we will need to initialize and connect the nodes to form a tree as shown in the figure above:
|
|
We are now ready to implement any of the tree traversal algorithms.
make sure to import ArrayList from
java.util.ArrayList
.
Pre Order Traversal
|
|
In Order Traversal
|
|
Post Order Traversal
|
|
Calling the various functions within main
|
|
The complete tree traversal algorithms code in Java
|
|
The output:
[Running] cd "/Users/mikeck/Desktop/Java/" && javac Tree.java && java Tree
[5, 4, 1, 2, 6]
[1, 4, 2, 5, 6]
[1, 2, 4, 6, 5]
[Done] exited with code=0 in 4.213 seconds
Thank you for reading. Feel free to contact me if you have any question, comment or suggestion. 🎉