Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. Note that if multiple nodes at same level pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.
Output: [[4], [2], [1, 5, 6], [3, 8], [7], [9]] Explanation: The below image shows the horizontal distances used to print vertical traversal starting from the leftmost level to the rightmost level.
The idea is to traverse the tree once and get the minimum and maximum horizontal distance with respect to root. For the tree shown above, minimum distance is -2 (for node with value 4) and maximum distance is 3 (For node with value 9). Once we have maximum and minimum distances from root, we iterate for each vertical line at distance minimum to maximum from root, and for each vertical line traverse the tree and print the nodes which lie on that vertical line.
Output
[ 4 ] [ 2 ] [ 1 5 6 ] [ 3 8 ] [ 7 ] [ 9 ]
Time Complexity: O(n2), Time complexity of above algorithm is O(w*n) where w is width of Binary Tree and n is number of nodes in Binary Tree. In worst case, the value of w can be O(n). Auxiliary Space: O(h), space use by memory stack, where h is height of the tree.
Please refer the below posts for optimised solutions.