Skip to content

Commit 76cf2bb

Browse files
committed
adding matlab implementation to tree traversal algorithm
1 parent fc01840 commit 76cf2bb

File tree

1 file changed

+6
-1
lines changed

1 file changed

+6
-1
lines changed

contents/tree_traversal/tree_traversal.md

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -178,6 +178,11 @@ In this case, the first node visited is at the bottom of the tree and moves up t
178178
[import:64-82, lang:"matlab"](code/matlab/tree.m)
179179
{% endmethod %}
180180

181+
<p>
182+
<img class="center" src="res/DFS_in.png" width="500" />
183+
</p>
184+
185+
181186
The order here seems to be some mix of the other 2 methods and works through the binary tree from left to right.
182187

183188
Now, at this point, it might seem that the only way to search through a recursive data structure is with recursion, but this is not necessarily the case! Rather surprisingly, we can perform a DFS non-recursively by using a stack, which are data structures that hold multiple elements, but only allow you to interact with the very last element you put in. The idea here is simple:
@@ -231,7 +236,7 @@ In code, it looks like this:
231236
All this said, there are a few details about DFS that might not be ideal, depending on the situation. For example, if we use DFS on an incredibly long tree, we will spend a lot of time going further and further down a single branch without searching the rest of the data structure. In addition, it is not the natural way humans would order a tree if asked to number all the nodes from top to bottom. I would argue a more natural traversal order would look something like this:
232237

233238
<p>
234-
<img class="center" src="res/BFS_simple.png" width="500" />
239+
<img class="center" src="res/BFS_simple.png" width="500" />
235240
</p>
236241

237242
And this is exactly what Breadth-First Search (BFS) does! On top of that, it can be implemented in the same way as the `DFS_stack(...)` function above, simply by swapping the `stack` for a `queue`, which is similar to a stack, except that it only allows you to interact with the very first element instead of the last. In code, this looks something like:

0 commit comments

Comments
 (0)