Skip to content

Instantly share code, notes, and snippets.

@rishi93
Created December 16, 2017 16:33
Show Gist options
  • Select an option

  • Save rishi93/685612d194001c9ec2b79ebcac97f46c to your computer and use it in GitHub Desktop.

Select an option

Save rishi93/685612d194001c9ec2b79ebcac97f46c to your computer and use it in GitHub Desktop.
Binary Tree Level order traversal
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class BinaryTree:
def __init__(self):
self.root = None
def printLevelOrder(self):
queue = []
queue.append(self.root)
while len(queue) > 0:
node = queue.pop(0)
print(node.data, end = ' ')
if node.left is not None:
queue.append(node.left)
if node.right is not None:
queue.append(node.right)
tree = BinaryTree()
tree.root = Node(5)
tree.root.left = Node(3)
tree.root.right = Node(7)
tree.root.left.left = Node(2)
tree.root.left.right = Node(4)
tree.root.right.left = Node(6)
tree.root.right.right = Node(8)
print("The level order traversal of the tree is:")
tree.printLevelOrder()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment