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 map:
|
|
We are now ready to implement any of the tree traversal algorithms.
Will make use of Elixir’s pattern matching to accomodate what happens when their is an empty list, and what happens when the traversal gets to the leaves. That is why we have three different functions, which look kinda similar, but take different arguments.
Pre Order Traversal
|
|
In Order Traversal
|
|
Post Order Traversal
|
|
Calling the various functions
|
|
The complete tree traversal algorithms code in Elixir
|
|
The output:
[Running] elixir "/Volumes/MAC/d/Algorithms/tree_traversal.exs"
ABCDE
CBDAE
CDBEA
[Done] exited with code=0 in 3.37 seconds
Thank you for reading. Feel free to contact me if you have any question, comment or suggestion. 🎉