Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # http://code2begin.blogspot.com
- # Program to print the nodes of the binary tree in vertical order using horizontal distance from the root node
- # node class
- class node:
- def __init__(self, element):
- self.data = element
- self.hd = -1
- self.left = None
- self.right = None
- # function to print the nodes of the binary tree in vertical order
- # using horizontal distance of a node from the root node
- def vertical_order(root):
- if root is None:
- return
- # initialize a map and queue
- # we will use iterative BFS traversal to solve this
- M = dict()
- Q = list()
- # push root in queue and initialize horizontal distance
- Q.append(root)
- horizontal_distance = root.hd
- while len(Q) > 0:
- current = Q[0]
- del Q[0]
- if current.hd in M.keys():
- M[current.hd].append(current.data)
- else:
- M[current.hd] = [current.data]
- # update horizontal distance of the left child and put it in the queue
- if current.left is not None:
- current.left.hd = current.hd - 1
- Q.append(current.left)
- # update horizontal distance of the right child and put it in the queue
- if current.right is not None:
- current.right.hd = current.hd + 1
- Q.append(current.right)
- # printing the contents of the map
- for horizontal_distance, elements in zip(M.keys(), M.values()):
- print("Nodes at " + str(horizontal_distance) + " : " + str(elements))
- 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
- print("Vertical order traversal of the binary tree is : ")
- vertical_order(head)
Add Comment
Please, Sign In to add comment