Last active
September 18, 2018 06:25
-
-
Save raytroop/0df9535eae068b68709e88c770a0530b to your computer and use it in GitHub Desktop.
binary tree traversal generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from queue import deque | |
class tree: | |
def __init__(self, x): | |
self.data = x | |
self.left = None | |
self.right = None | |
trees_queue = deque() | |
# generate tree | |
x = 0 | |
root = tree(x) | |
trees_queue.append(root) | |
def generate_tree(this_queue): | |
nb_node = 1 | |
global x | |
while nb_node < 7: | |
node = this_queue.popleft() | |
x += 1 | |
node.left = tree(x) | |
x += 1 | |
node.right = tree(x) | |
this_queue.append(node.left) | |
this_queue.append(node.right) | |
nb_node += 2 | |
generate_tree(trees_queue) | |
########################################################################## | |
# level traversal | |
nodes_queue = deque() | |
nodes_queue.append(root) | |
def level_traversal(this_queue): | |
while this_queue: | |
node = this_queue.popleft() | |
# print(node.data) | |
yield node.data | |
if node.left is not None: | |
nodes_queue.append(node.left) | |
if node.right is not None: | |
nodes_queue.append(node.right) | |
# level_traversal(nodes_queue) | |
for var in level_traversal(nodes_queue): | |
print(var) | |
# 0 | |
# 1 | |
# 2 | |
# 3 | |
# 4 | |
# 5 | |
# 6 | |
########################################################################## | |
# BUG recursive pre-order traversal | |
def travPre_p(node): | |
if node is None: | |
return | |
yield node.data | |
travPre_p(node.left) | |
travPre_p(node.right) | |
for var in travPre_p(root): | |
print(var) | |
# 0 | |
########################################################################## | |
# An iterative process to print preorder traveral of BT | |
def iterativePreorder(node): | |
# Base CAse | |
if node is None: | |
return | |
# create an empty stack and push node to it | |
nodeStack = [] | |
nodeStack.append(node) | |
# Pop all items one by one. Do following for every popped item | |
# a) print it | |
# b) push its right child | |
# c) push its left child | |
# Note that right child is pushed first so that left | |
# is processed first */ | |
while nodeStack: | |
# Pop the top item from stack and print it | |
node = nodeStack.pop() | |
yield node.data | |
# Push right and left children of the popped node | |
# to stack | |
if node.right is not None: | |
nodeStack.append(node.right) | |
if node.left is not None: | |
nodeStack.append(node.left) | |
for var in iterativePreorder(root): | |
print(var) | |
# 0 | |
# 1 | |
# 3 | |
# 4 | |
# 2 | |
# 5 | |
# 6 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
recursive
dont work withyield