#Driver Code Starts
# Python code of Vertical Traversal
# using Brute Force
class Node:
def __init__(self, x):
self.data = x
self.left = None
self.right = None
#Driver Code Ends
# A utility function to find min and max
# distances with respect to root.
def findMinMax(node, minMax, hd):
if node is None:
return
# Update min and max
if hd < minMax[0]:
minMax[0] = hd
elif hd > minMax[1]:
minMax[1] = hd
# Recur for left and right subtrees
findMinMax(node.left, minMax, hd - 1)
findMinMax(node.right, minMax, hd + 1)
# A utility function to collect all
# nodes on a given vertical line_no.
def collectVerticalLine(node, lineNo, hd, res):
if node is None:
return
# If this node is on the given vertical line
if hd == lineNo:
res.append(node.data)
# Recur for left and right subtrees
collectVerticalLine(node.left, lineNo, hd - 1, res)
collectVerticalLine(node.right, lineNo, hd + 1, res)
# The main function that returns a list of lists
# of nodes in vertical order
def verticalOrder(root):
res = []
# Find min and max distances with respect to root
minMax = [0, 0]
findMinMax(root, minMax, 0)
# Iterate through all possible vertical lines
for lineNo in range(minMax[0], minMax[1] + 1):
verticalNodes = []
collectVerticalLine(root, lineNo, 0, verticalNodes)
res.append(verticalNodes)
return res
#Driver Code Starts
if __name__ == "__main__":
# Create binary tree
# 1
# / \
# 2 3
# / \ / \
# 4 5 6 7
# \ \
# 8 9
root = Node(1)
root.left = Node(2)
root.right = Node(3)
root.left.left = Node(4)
root.left.right = Node(5)
root.right.left = Node(6)
root.right.right = Node(7)
root.right.left.right = Node(8)
root.right.right.right = Node(9)
res = verticalOrder(root)
# Print grouped vertical nodes
for temp in res:
print("[", " ".join(map(str, temp)), "]", end=" ")
print()
#Driver Code Ends