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 can be printed in any order. Expected time complexity is O(n)
A node x is there in output if x is the topmost node at its horizontal distance. Horizontal distance of left child of a node x is equal to horizontal distance of x minus 1, and that of right child is horizontal distance of x plus 1.
1 / \ 2 3 / \ / \ 4 5 6 7 Top view of the above binary tree is 4 2 1 3 7 1 / \ 2 3 \ 4 \ 5 \ 6 Top view of the above binary tree is 2 1 3 6
- The idea here is to observe that, if we try to see a tree from its top, then only the nodes which are at top in vertical order will be seen.
- Start BFS from root. Maintain a queue of pairs comprising of node(Node *) type and vertical distance of node from root. Also, maintain a map which should store the node at a particular vertical distance.
- While processing a node, just check if any node is there in the map at that vertical distance.
- If any node is there, it means the node can’t be seen from top, do not consider it. Else, if there is no node at that vertical distance, store that in map and consider for top view.
Below is the implementation based on above approach:
Following are nodes in top view of Binary Tree 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 top view of Binary Tree | Set 2
- 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
- Sum of nodes in the right view of the given binary tree
- Sum of nodes in the left view of the given binary tree
- Print Left View of a 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 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
- Bottom View of a Binary Tree
- Right view of Binary Tree using Queue
- Bottom View of a Binary Tree using Recursion
- Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
- Print Binary Tree levels in sorted order | Set 3 (Tree given as array)
- Print nodes between two given level numbers of a binary tree
- 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 email@example.com. 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.