Skip to content

Commit fd6b7a6

Browse files
authored
Updated tree traversal chapter (#979)
1 parent b17f07b commit fd6b7a6

File tree

2 files changed

+12
-25
lines changed

2 files changed

+12
-25
lines changed

contents/tree_traversal/code/python/tree_traversal.py

+10-23
Original file line numberDiff line numberDiff line change
@@ -46,31 +46,18 @@ def dfs_recursive_inorder_btree(node):
4646

4747

4848
def dfs_stack(node):
49-
stack = []
50-
stack.append(node)
51-
52-
temp = None
53-
54-
while len(stack) > 0:
55-
print(stack[-1].data, end=' ')
56-
temp = stack.pop()
57-
58-
for child in temp.children:
59-
stack.append(child)
60-
49+
stack = [node]
50+
while stack:
51+
node = stack.pop()
52+
stack.extend(node.children)
53+
print(node.data, end=' ')
6154

6255
def bfs_queue(node):
63-
queue = []
64-
queue.append(node)
65-
66-
temp = None
67-
68-
while len(queue) > 0:
69-
print(queue[0].data, end=' ')
70-
temp = queue.pop(0)
71-
72-
for child in temp.children:
73-
queue.append(child)
56+
queue = [node]
57+
while queue:
58+
node = queue.pop(0)
59+
queue.extend(node.children)
60+
print(node.data)
7461

7562

7663
def main():

contents/tree_traversal/tree_traversal.md

+2-2
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ In code, it looks like this:
231231
{% sample lang="js" %}
232232
[import:53-60, lang:"javascript"](code/javascript/tree.js)
233233
{% sample lang="py" %}
234-
[import:48-59, lang:"python"](code/python/tree_traversal.py)
234+
[import:48-53, lang:"python"](code/python/tree_traversal.py)
235235
{% sample lang="scratch" %}
236236
<p>
237237
<img class="center" src="code/scratch/dfs-stack.svg" style="width:70%" />
@@ -284,7 +284,7 @@ And this is exactly what Breadth-First Search (BFS) does! On top of that, it can
284284
{% sample lang="js" %}
285285
[import:62-69, lang:"javascript"](code/javascript/tree.js)
286286
{% sample lang="py" %}
287-
[import:62-72, lang:"python"](code/python/tree_traversal.py)
287+
[import:55-60, lang:"python"](code/python/tree_traversal.py)
288288
{% sample lang="scratch" %}
289289
<p>
290290
<img class="center" src="code/scratch/bfs.svg" style="width:70%" />

0 commit comments

Comments
 (0)