Print a Binary Tree in Vertical OrderPrint a binary tree vertically given one. The vertical order traversal is demonstrated in the example below. ![]() The goal is to make one pass through the tree and measure the minimum and maximum horizontal distances from the root. The smallest distance for the tree depicted above is -2 (for node with value 4), while the greatest distance is 3. (For node with value 9). After determining the maximum and minimum distances from the root, we repeat for each vertical line from the minimum to the greatest distance from the root, walk the tree for each vertical line, and output the nodes that are along that vertical line. AlgorithmCode in C++The aforesaid algorithm is implemented as follows. Output: Vertical order traversal is 4 2 1 5 6 3 8 7 9 Time Complexity: The aforementioned technique has an O(w*n) time complexity, where w is the width of the binary tree and n is the number of nodes. In the worst scenario, the value of w may be O(n) (take a whole tree as an example) and the time complexity could increase to O. (n2). The method covered in this post can help tackle this issue more effectively. Soon, we'll talk about whole algorithms and how to put more effective techniques into practise. Method -2 - More Optimized Method: (With MinHeaps)![]() Algorithm
NOTE:
Code in C++The aforesaid algorithm is implemented as follows. Output: Vertical order traversal is 4 2 1 5 6 3 8 7 9 Time Complexity: O(N*LogN) Time Reason:
Auxiliary Space: O(N) Reason:
N is the Size of the Binary Tree. (Total no. of nodes)
Next TopicTournament Tree (Winner Tree)
|