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 1 2 3 6
- Print Nodes in Top View of Binary Tree
- Print nodes in top view of Binary Tree | Set 2
- 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 nodes between two given levels in Binary Tree
- Print all nodes in a binary tree having K leaves
- Print Levels of all nodes in a Binary Tree
- Print all full nodes in a Binary Tree
- Print all even nodes of Binary Search Tree
- Print path between any two nodes in a Binary Tree
- Print all internal nodes of a Binary tree
- Print all leaf nodes of a Binary Tree from left to right
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.
Improved By : andrew1234