Skip to content

Python for Tree Traversal #1

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 2 commits into from Sep 10, 2017
Merged
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
80 changes: 80 additions & 0 deletions chapters/fundamental_algorithms/tree_traversal.md
Original file line number Diff line number Diff line change
Expand Up @@ -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--------------------------------------//
*
Expand Down Expand Up @@ -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()
```