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
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Print nodes in the Top View of Binary Tree | Set 3
- Print Nodes in Top View of Binary Tree
- Sum of nodes in top view of binary tree
- Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in the left view of the given binary tree
- Sum of nodes in bottom view of Binary Tree
- Print Right View of a Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Print Bottom-Right View of a Binary Tree
- Print Left View of a Binary Tree
- Print All Leaf Nodes of a Binary Tree from left to right | Set-2 ( Iterative Approach )
- Print path between any two nodes in a Binary Tree | Set 2
- Count the nodes of the tree which make a pangram when concatenated with the sub-tree nodes
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Bottom View of a Binary Tree
- Right view of Binary Tree using Queue
- Bottom View of a Binary Tree using Recursion
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print nodes between two given level numbers of a binary tree
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.