# Print vertical order of binary tree in python

Python program for Print vertical order of binary tree. Here problem description and other solutions.

``````#  Python 3 program for
#  Print vertical traversal of binary tree

#  Binary Tree Node
class TreeNode :
def __init__(self, data) :
#  Set node value
self.data = data
self.left = None
self.right = None

#  Create Q node
class QNode :
def __init__(self, node) :
self.data = node
self.next = None
self.distance = 0

class MyQueue :
def __init__(self) :
self.tail = None
self.count = 0

def size(self) :
return self.count

def isEmpty(self) :
return self.count == 0

#  Add new node of queue
def enqueue(self, value, d) :
#  Create a new node
node = QNode(value)
#  Add first element into queue
else :
#  Add node at the end using tail
self.tail.next = node
#  Set node distance
node.distance = d

self.count += 1
self.tail = node

#  Delete a element into queue
def dequeue(self) :
#  Empty Queue
return

#  Visit next node
self.count -= 1
#  When deleting a last node of linked list
self.tail = None

#  Get front node
def peek(self) :
return None

class BinaryTree :
def __init__(self) :
self.root = None

#  Find vertical elements
def getVerticalNode(self, record) :
if (self.root != None) :
q = MyQueue()
q.enqueue(self.root, 0)
node = self.root
d = 0
while (q.isEmpty() == False) :
#  Get distance
if (node.left != None) :
q.enqueue(node.left, d - 1)

if (node.right != None) :
q.enqueue(node.right, d + 1)

if (not(d in record.keys())) :
record[d] = []

record.get(d).append(node.data)
#  Remove current node
q.dequeue()
node = q.peek()

def verticalView(self) :
#  This is store result
record = dict()
self.getVerticalNode(record)
distance = 0
#  Find first leftmost element
while ((distance - 1 in record.keys())) :
distance -= 1

#  Display result
while ((distance in record.keys())) :
print(record.get(distance))
distance += 1

def main() :
#  Create new tree
tree = BinaryTree()
#  Binary Tree
#  -------------
#      10
#     /  \
#    2    4
#   /    / \
#  3    6   5
#   \    \
#    9    7
#     \    \
#      1    11
tree.root = TreeNode(10)
tree.root.left = TreeNode(2)
tree.root.left.left = TreeNode(3)
tree.root.left.left.right = TreeNode(9)
tree.root.right = TreeNode(4)
tree.root.right.right = TreeNode(5)
tree.root.right.left = TreeNode(6)
tree.root.right.left.right = TreeNode(7)
tree.root.right.left.right.right = TreeNode(11)
tree.root.left.left.right.right = TreeNode(1)
#  Test
tree.verticalView()

if __name__ == "__main__": main()``````

Output

``````
[2, 9]
[10, 6, 1]
[4, 7]
[5, 11]``````

## Comment

Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.