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
- 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
- Sum of nodes in bottom view of Binary Tree
- Print Right View of a Binary Tree
- Print Left View of a Binary Tree
- Iterative Method To Print Left View of a Binary Tree
- Print all internal nodes of a Binary tree
- Print Levels of all nodes in a Binary Tree
- Print all full nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print path between any two nodes in a Binary Tree
- Print all even nodes of Binary Search Tree
- Print all nodes in a binary tree having K leaves
- Print leftmost and rightmost nodes 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.