Skip to content

Commit 53133cd

Browse files
authored
Merge pull request #1 from KingFredrickVI/master
Python for Tree Traversal
2 parents 61cce77 + fcbd1e5 commit 53133cd

File tree

1 file changed

+80
-0
lines changed

1 file changed

+80
-0
lines changed

chapters/fundamental_algorithms/tree_traversal.md

+80
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ Do you think we should be using real code snippets in the main text or stick the
114114
115115
# Example Code
116116
117+
### C++
118+
117119
```cpp
118120
/*-------------simple_tree_traversal.cpp--------------------------------------//
119121
*
@@ -213,3 +215,81 @@ int main(){
213215
}
214216
215217
```
218+
219+
### Python
220+
221+
```Python
222+
223+
# /*-------------simple_tree_traversal.py--------------------------------------//
224+
# *
225+
# * Purpose: To implement basic tree traversal in Python.
226+
# *
227+
# * Run: python simple_tree_traversal.py
228+
# *
229+
# *-----------------------------------------------------------------------------*/
230+
231+
232+
class Node:
233+
234+
def __init__(self):
235+
self.data = None
236+
self.children = []
237+
238+
239+
def create_tree(node, num_row, num_child):
240+
node.data = num_row
241+
242+
if num_row > 0:
243+
for i in range(num_child):
244+
child = create_tree(Node(), num_row-1, num_child)
245+
node.children.append(child)
246+
247+
return node
248+
249+
def DFS_recursive(node):
250+
if len(node.children) > 0:
251+
print node.data
252+
253+
for child in node.children:
254+
DFS_recursive(child)
255+
256+
def DFS_stack(node):
257+
stack = []
258+
stack.append(node)
259+
260+
temp = None
261+
262+
while len(stack) > 0:
263+
print stack[-1].data
264+
temp = stack.pop()
265+
266+
for child in temp.children:
267+
stack.append(child)
268+
269+
def BFS_queue(node):
270+
queue = []
271+
queue.append(node)
272+
273+
temp = None
274+
275+
while len(queue) > 0:
276+
print queue[0].data
277+
temp = queue.pop(0)
278+
279+
for child in temp.children:
280+
queue.append(child)
281+
282+
def main():
283+
tree = create_tree(Node(), 3, 3)
284+
285+
print "Recursive:"
286+
DFS_recursive(tree)
287+
288+
print "Stack:"
289+
DFS_stack(tree)
290+
291+
print "Queue:"
292+
BFS_queue(tree)
293+
294+
main()
295+
```

0 commit comments

Comments
 (0)