Print nodes in top view of Binary Tree | Set 2
Top view of a binary tree is the set of nodes visible when the tree is viewed from the top. Given a binary tree, print the top view of it. The output nodes should be printed from left to right.
Note: A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of the left child of a node x is equal to the horizontal distance of x minus 1, and that of right child is the horizontal distance of x plus 1.
Input: 1 / \ 2 3 / \ / \ 4 5 6 7 Output: Top view: 4 2 1 3 7 Input: 1 / \ 2 3 \ 4 \ 5 \ 6 Output: Top view: 2 1 3 6
The idea is to do something similar to Vertical Order Traversal. Like Vertical Order Traversal, we need to group nodes of same horizontal distance together. We do a level order traversal so that the topmost node at a horizontal node is visited before any other node of same horizontal distance below it. A Map is used to map the horizontal distance of the node with the node’s Data and vertical distance of the node.
Below is the implementation of the above approach:
Top View : 2 1 3 6
Time complexity: O(n) where n is number of nodes of binary tree
Auxiliary space: O(n) for call stack