Skip to content

Updated tree traversal chapter #979

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Dec 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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