<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0" xmlns:atom="http://www.w3.org/2005/Atom" xmlns:dc="http://purl.org/dc/elements/1.1/">
  <channel>
    <title>DEV Community: Cristhian Fuertes</title>
    <description>The latest articles on DEV Community by Cristhian Fuertes (@crisefd).</description>
    <link>https://dev.to/crisefd</link>
    <image>
      <url>https://media2.dev.to/dynamic/image/width=90,height=90,fit=cover,gravity=auto,format=auto/https:%2F%2Fdev-to-uploads.s3.amazonaws.com%2Fuploads%2Fuser%2Fprofile_image%2F309136%2F3b89ef3c-0ebf-40b8-b3d4-01500a3e8119.jpeg</url>
      <title>DEV Community: Cristhian Fuertes</title>
      <link>https://dev.to/crisefd</link>
    </image>
    <atom:link rel="self" type="application/rss+xml" href="https://dev.to/feed/crisefd"/>
    <language>en</language>
    <item>
      <title>Tree Traversal With Elixir</title>
      <dc:creator>Cristhian Fuertes</dc:creator>
      <pubDate>Sun, 05 Jan 2020 21:01:51 +0000</pubDate>
      <link>https://dev.to/crisefd/tree-traversal-with-elixir-lc5</link>
      <guid>https://dev.to/crisefd/tree-traversal-with-elixir-lc5</guid>
      <description>&lt;p&gt;This is a simple implementation of depth-first and breadth-first traverse algorithms in Elixir.&lt;/p&gt;

&lt;p&gt;First, let's talk about &lt;a href="https://en.wikipedia.org/wiki/Elixir_(programming_language)" rel="noopener noreferrer"&gt;Elixir&lt;/a&gt;: Elixir is a functional, dynamically-typed, general purpose programming language design for concurrency. It's based on the Erlang programming language and runs on its virtual machine (BEAM).&lt;/p&gt;

&lt;p&gt;And tree traversal algorithms:&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Trees&lt;/strong&gt; are a recursive data structured that should be in every programmer's arsenal. A tree can be either leaf node or a node that contains one or more subtrees. Nodes can carry data, typically a node value and a node key.&lt;br&gt;
Trees differ from list in that list are linear structures and trees have a branching structure. Each element in a list points to the rest of list (a linked-list). Whereas each element in a tree points to one or more subtrees.&lt;br&gt;
Trees are a kind of graph and they come in different kinds depending of the branching structure and node contents; unary, binary, binary search and N-ary trees are some examples.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Traversing&lt;/strong&gt; a tree means to apply some operation on its nodes in a well-defined order.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Depth-first traverse&lt;/strong&gt; algorithm consists of for each node, visit first the node itself, then start visiting from the leftmost subtree until you reach the rightmost subtree. Repeat this for each subtree until all nodes have been visited.&lt;br&gt;
The algorithm uses a &lt;a href="https://www.geeksforgeeks.org/stack-data-structure/" rel="noopener noreferrer"&gt;stack&lt;/a&gt; -- implicitly or explicitly -- to store the nodes that need to be visited.&lt;/p&gt;

&lt;p&gt;&lt;strong&gt;Breadth-first traverse&lt;/strong&gt; algorithm consists of visiting each node at depth 0, then each node at depth 1, then depth 3, and so forth until all nodes have been visited.&lt;br&gt;
This algorithm uses a &lt;a href="https://www.geeksforgeeks.org/queue-data-structure/" rel="noopener noreferrer"&gt;queue&lt;/a&gt; -- implicitly or explicitly -- instead of a stack to store the nodes before visit them.&lt;/p&gt;
&lt;h2&gt;
  
  
  Let's get to the code.
&lt;/h2&gt;

&lt;p&gt;First let's create a &lt;em&gt;elixir_trees&lt;/em&gt; project:&lt;/p&gt;

&lt;p&gt;&lt;code&gt;mix new elixir_trees&lt;/code&gt;&lt;/p&gt;

&lt;p&gt;And define our tree data estructure in &lt;code&gt;elixir_trees/lib/tree.ex&lt;/code&gt; like this:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fo41frm8k20uvnv1vjvvw.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fo41frm8k20uvnv1vjvvw.png" alt="Tree data-type"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;A tree is struct with the fields: value(the data to perform operations with), key (an optional unique id for the node) and children (the subtrees). Also we add the type spec to improve consistency and readability.&lt;/p&gt;

&lt;p&gt;Next we define the tree traversal module in &lt;code&gt;elixir_trees/lib/tree_traversal.ex&lt;/code&gt; and define the types for the function specs and aliases for the tree datatype:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fh3aulwkzxcchw3sijmtm.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fh3aulwkzxcchw3sijmtm.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Now we write our functions, let's start with depth-first:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fras6697jjhfxt5xpufe0.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fras6697jjhfxt5xpufe0.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Lines 54-56 declare and add the &lt;em&gt;typespec&lt;/em&gt; to the function. &lt;strong&gt;dfs&lt;/strong&gt; receives 3 arguments: a stack to store the nodes, a function operation that will be apply when visiting each node and history which is a list with accumulated result of applying the function operation while traversing the tree. &lt;br&gt;
As specify at lines 11-12, the operation function receives 3 arguments, the node value, the node key and the accumulated history, and returns a tuple with the result of the operation and a atom telling the algorithm wether to continue traversing or to stop.&lt;br&gt;
Let's take a look at some simple valid operation functions to pass to the algorithm:&lt;br&gt;
&lt;/p&gt;

&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn (x, _, _) when x &amp;lt; 0 -&amp;gt; {:stop, x}
   (x, _, _) -&amp;gt; {:continue, x} 
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;





&lt;div class="highlight js-code-highlight"&gt;
&lt;pre class="highlight plaintext"&gt;&lt;code&gt;fn (x, _, []) -&amp;gt; {:continue, x}
   (x, _, h) -&amp;gt; {:continue, x + hd(h)} 
end
&lt;/code&gt;&lt;/pre&gt;

&lt;/div&gt;



&lt;p&gt;The first one checks wether negative values exists in the tree and stop as soon as it finds one, it continues otherwise. And the second one sums all the values of the nodes in the tree.&lt;/p&gt;

&lt;p&gt;Now, line 58 deals with base case when the stack is empty and returns the traverse history as a result, the stack is implemented a regular list. The result of visiting each node is arrange from last to first i.e the result of visiting the root of the tree is the last element in the history.&lt;br&gt;
Line 60 deals with the case where the stack is non-empty and uses patter-matching to get the tree node properties and we pass that to the &lt;code&gt;next/7&lt;/code&gt; function along with &lt;code&gt;dfs/3&lt;/code&gt; function to apply and indirect recursive call and continue process.&lt;/p&gt;

&lt;p&gt;&lt;code&gt;next/7&lt;/code&gt; is defined as:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Foee9a9zo27ddzphb0tf4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Foee9a9zo27ddzphb0tf4.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;The function applies and checks the result of applying the function operation to the node, deciding whether to stop or continue traversing. If the operation result tells it to stop it simply add the result value to the existing history and terminates, if not, it uses the &lt;code&gt;tree_insert/2&lt;/code&gt; function to scheduled the next nodes to be visit (we'll explaning this one later) and pipes down the result to the caller function, in this case &lt;code&gt;dfs/3&lt;/code&gt;. &lt;/p&gt;

&lt;p&gt;And that's all for the dfs function now, let's implement the breadth-first search one:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyt3kmzhzq4au3p1tly8c.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyt3kmzhzq4au3p1tly8c.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;This is pretty much the same as &lt;code&gt;dfs/3&lt;/code&gt;. The only differences are the the base case at line 71 that doesn't check for an empty stack anymore, it checks for an empty queue, same for lines 74-77, instead of popping a stack we pop a queue. The queue we are using is the &lt;a href="https://en.wikipedia.org/wiki/Amortized_analysis" rel="noopener noreferrer"&gt;amortized queue&lt;/a&gt; &lt;a href="http://erlang.org/doc/man/queue.html" rel="noopener noreferrer"&gt;implementation in Erlang&lt;/a&gt;. After that we do the same as before, we pass along node fields, queue and function to &lt;code&gt;next/7&lt;/code&gt;.&lt;/p&gt;

&lt;p&gt;Now that we've seen the implementation of dfs and bfs algorithms let's explain the missing helper functions &lt;code&gt;tree_insert/2&lt;/code&gt; and &lt;code&gt;apply_operation/4&lt;/code&gt;:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fynrxq09b0rzgsh289u5l.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fynrxq09b0rzgsh289u5l.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;tree_insert/2&lt;/code&gt; deals with pushing/popping nodes to the queue/stack.&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyg1u5u2ouj360rdrsslc.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fyg1u5u2ouj360rdrsslc.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;&lt;code&gt;apply_operation/4&lt;/code&gt; checks the arity of the operation function and raises an exception if it's not 3, otherwise it applies the function to the arguments and returns the result.&lt;/p&gt;

&lt;p&gt;Finally all that's missing is main function to wrap it all up:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fpb7z3orh4hqegxyrwc70.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fpb7z3orh4hqegxyrwc70.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;Traverse receives the tree, the operation function and an atom with the name of the algorithm we wish to use.&lt;br&gt;
And The initial stack and queue are initialized by this pair:&lt;/p&gt;

&lt;p&gt;&lt;a href="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgtyrkkkovljsmftle3e4.png" class="article-body-image-wrapper"&gt;&lt;img src="https://media.dev.to/dynamic/image/width=800%2Cheight=%2Cfit=scale-down%2Cgravity=auto%2Cformat=auto/https%3A%2F%2Fthepracticaldev.s3.amazonaws.com%2Fi%2Fgtyrkkkovljsmftle3e4.png" alt="Alt Text"&gt;&lt;/a&gt;&lt;/p&gt;

&lt;p&gt;You can find the full source code &lt;a href="https://github.com/crisefd/elixir_trees/tree/master/lib" rel="noopener noreferrer"&gt;here&lt;/a&gt;&lt;/p&gt;

</description>
      <category>elixir</category>
      <category>trees</category>
    </item>
  </channel>
</rss>
