Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to print the width of a given binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.left = None
- self.right = None
- # function to print the width of the binary tree
- def width(root):
- if root is None:
- return 0
- # creating a Queue for storing node for level wise traversal
- Q = list()
- Q.append(root)
- result = 0
- while len(Q) > 0:
- # store the current size of the Q
- count = len(Q)
- # find out the max width
- result = max(result, count)
- while count != 0:
- # pop the first node from the queue
- NODE = Q[0]
- del Q[0]
- # 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
- # return the final width
- return result
- 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)
- print("Width of the above binary tree is : " + str(width(head)))
Add Comment
Please, Sign In to add comment