From bb62afd9fbf4eefb4617aa00224432fe5f74b89a Mon Sep 17 00:00:00 2001 From: KingFredrickVI Date: Sun, 10 Sep 2017 18:32:05 -0400 Subject: [PATCH 1/2] Added Python tree traversal example --- .../fundamental_algorithms/tree_traversal.md | 80 +++++++++++++++++++ 1 file changed, 80 insertions(+) diff --git a/chapters/fundamental_algorithms/tree_traversal.md b/chapters/fundamental_algorithms/tree_traversal.md index ad37c0d86..5b800f222 100644 --- a/chapters/fundamental_algorithms/tree_traversal.md +++ b/chapters/fundamental_algorithms/tree_traversal.md @@ -114,6 +114,8 @@ Do you think we should be using real code snippets in the main text or stick the # Example Code +## C++ + ```cpp /*-------------simple_tree_traversal.cpp--------------------------------------// * @@ -213,3 +215,81 @@ int main(){ } ``` + +## Python + +```Python + +# /*-------------simple_tree_traversal.py--------------------------------------// +# * +# * Purpose: To implement basic tree traversal in Python. +# * +# * Run: python simple_tree_traversal.py +# * +# *-----------------------------------------------------------------------------*/ + + +class Node: + + def __init__(self): + self.data = None + self.children = [] + + +def create_tree(node, num_row, num_child): + node.data = num_row + + if num_row > 0: + for i in range(num_child): + child = create_tree(Node(), num_row-1, num_child) + node.children.append(child) + + return node + +def DFS_recursive(node): + if len(node.children) > 0: + print node.data + + for child in node.children: + DFS_recursive(child) + +def DFS_stack(node): + stack = [] + stack.append(node) + + temp = None + + while len(stack) > 0: + print stack[-1].data + temp = stack.pop() + + for child in temp.children: + stack.append(child) + +def BFS_queue(node): + queue = [] + queue.append(node) + + temp = None + + while len(queue) > 0: + print queue[0].data + temp = queue.pop(0) + + for child in temp.children: + queue.append(child) + +def main(): + tree = create_tree(Node(), 3, 3) + + print "Recursive:" + DFS_recursive(tree) + + print "Stack:" + DFS_stack(tree) + + print "Queue:" + BFS_queue(tree) + +main() +``` From fcbd1e50fc98693a280ca7cc75dbe0a91ed5d005 Mon Sep 17 00:00:00 2001 From: KingFredrickVI Date: Sun, 10 Sep 2017 18:33:39 -0400 Subject: [PATCH 2/2] Made headers smaller --- chapters/fundamental_algorithms/tree_traversal.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/chapters/fundamental_algorithms/tree_traversal.md b/chapters/fundamental_algorithms/tree_traversal.md index 5b800f222..eedf48bf7 100644 --- a/chapters/fundamental_algorithms/tree_traversal.md +++ b/chapters/fundamental_algorithms/tree_traversal.md @@ -114,7 +114,7 @@ Do you think we should be using real code snippets in the main text or stick the # Example Code -## C++ +### C++ ```cpp /*-------------simple_tree_traversal.cpp--------------------------------------// @@ -216,7 +216,7 @@ int main(){ ``` -## Python +### Python ```Python