Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to print the bottom view of the binary tree
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.hd = -1
- self.left = None
- self.right = None
- # function to print the bottom view of the binary tree
- def bottom_view(root):
- if root is None:
- return
- # we keep track of the horizontal distance of the node from the root node
- # to print the bottom view
- # hd = horizontal distance from the root node
- # creating a Queue for storing node for level wise traversal
- # and a map for mapping horizontal distances with the node data
- Q = []
- Map = dict()
- Q.append(root)
- while len(Q) > 0:
- # pop the first node from the queue
- p = Q[0]
- del Q[0]
- hd = p.hd
- Map[hd] = p.data
- # increase the horizontal distance from the root node in negative direction
- # and push the node on queue
- if p.left is not None:
- p.left.hd = hd - 1
- Q.append(p.left)
- # increase the horizontal distance from the root node in positive direction
- # and push the node on queue
- if p.right is not None:
- p.right.hd = hd + 1
- Q.append(p.right)
- # print the generated map
- print("Bottom view of the binary tree is : ")
- print(list(Map.values()))
- 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)
- head.hd = 0
- bottom_view(head)
Add Comment
Please, Sign In to add comment