Based on what i understood of Binary Tree, queue and recursion I implemented this Breadth First Search algorithm as follows. Do you have any suggestions to improve (in term of readability, good practice etc...) it?
# Definition for a binary tree node.
class Node(object):
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_print(self):
print(self.val)
if self.left:
self.left.preorder_print()
if self.right:
self.right.preorder_print()
return
def postorder_print(self):
if self.left:
self.left.postorder_print()
if self.right:
self.right.postorder_print()
print(self.val)
return
def inorder_print(self):
if self.left:
self.left.inorder_print()
print(self.val)
if self.right:
self.right.inorder_print()
return
def bread_traversal_print(self):
q=Queue()
q.push(self)
def bt():
#import pdb;pdb.set_trace
if not q:
return
node=q.pop()
if node:
if node.left:
q.push(node.left)
if node.right:
q.push(node.right)
print(node.val)
bt()
bt()
class Queue():
def __init__(self):
self.data = []
def push(self,elt):
self.data.append(elt)
def pop(self):
if self.data:
return self.data.pop(0)
def peek(self):
if self.data:
return self.data[0]
if __name__ == "__main__":
#input = [l for l in 'FDJBEGKACIH']
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
print("preorder:")
root.preorder_print()
print("postorder:")
root.postorder_print()
print("inorder:")
root.inorder_print()
print('bread :')
root.bread_traversal_print()
""" 1
2 3
4 5 6 7
[1 2 4 5 3 6 7]
"""
EDIT: Yes BFS for Breadth First Search would be more appropriate ;)