Skip to content

Commit

Permalink
Updated tree traversal chapter (algorithm-archivists#979)
Browse files Browse the repository at this point in the history
  • Loading branch information
ell-hol authored Dec 27, 2021
1 parent b17f07b commit fd6b7a6
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 25 deletions.
33 changes: 10 additions & 23 deletions contents/tree_traversal/code/python/tree_traversal.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,31 +46,18 @@ def dfs_recursive_inorder_btree(node):


def dfs_stack(node):
stack = []
stack.append(node)

temp = None

while len(stack) > 0:
print(stack[-1].data, end=' ')
temp = stack.pop()

for child in temp.children:
stack.append(child)

stack = [node]
while stack:
node = stack.pop()
stack.extend(node.children)
print(node.data, end=' ')

def bfs_queue(node):
queue = []
queue.append(node)

temp = None

while len(queue) > 0:
print(queue[0].data, end=' ')
temp = queue.pop(0)

for child in temp.children:
queue.append(child)
queue = [node]
while queue:
node = queue.pop(0)
queue.extend(node.children)
print(node.data)


def main():
Expand Down
4 changes: 2 additions & 2 deletions contents/tree_traversal/tree_traversal.md
Original file line number Diff line number Diff line change
Expand Up @@ -231,7 +231,7 @@ In code, it looks like this:
{% sample lang="js" %}
[import:53-60, lang:"javascript"](code/javascript/tree.js)
{% sample lang="py" %}
[import:48-59, lang:"python"](code/python/tree_traversal.py)
[import:48-53, lang:"python"](code/python/tree_traversal.py)
{% sample lang="scratch" %}
<p>
<img class="center" src="code/scratch/dfs-stack.svg" style="width:70%" />
Expand Down Expand Up @@ -284,7 +284,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
{% sample lang="js" %}
[import:62-69, lang:"javascript"](code/javascript/tree.js)
{% sample lang="py" %}
[import:62-72, lang:"python"](code/python/tree_traversal.py)
[import:55-60, lang:"python"](code/python/tree_traversal.py)
{% sample lang="scratch" %}
<p>
<img class="center" src="code/scratch/bfs.svg" style="width:70%" />
Expand Down

0 comments on commit fd6b7a6

Please sign in to comment.