Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to Left view of a binary tree iteratively
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.hd = -1
- self.left = None
- self.right = None
- # BFS itertative using queue for left view
- def left_view_iterative(root):
- if root is None:
- return
- # creating a Queue for storing node for level wise traversal
- Q = list()
- Q.append(root)
- level = 0
- max_level = 0
- print("Left view of the binary tree is : ")
- while len(Q):
- # store the current size of the Q
- count = len(Q)
- level += 1
- while count != 0:
- # pop the first node from the queue
- NODE = Q[0]
- del Q[0]
- if level > max_level:
- print(NODE.data, end=" ")
- max_level = level
- # push the left child on queue
- if NODE.left is not None:
- Q.append(NODE.left)
- # push the right child on queue
- if NODE.right is not None:
- Q.append(NODE.right)
- count -= 1
- print()
- head = node(1)
- head.left = node(2)
- head.right = node(3)
- head.left.left = node(4)
- head.left.right = node(5)
- head.right.right = node(6)
- head.left.left.right = node(7)
- head.right.right.left = node(8)
- head.left.left.right.left = node(9)
- head.left.left.right.left.left = node(10)
- head.right.right.left.right = node(11)
- left_view_iterative(head)
Add Comment
Please, Sign In to add comment