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 is to do something similar to vertical Order Traversal. Like vertical Order Traversal, we need to put 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. Hashing is used to check if a node at given horizontal distance is seen or not.
Following are nodes in top view of Binary Tree 2136
Time Complexity of the above implementation is O(n) where n is the number of nodes in the given binary tree. The assumption here is that add() and contains() methods of HashSet work in O(1) time.
This article is contributed by Rohan. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
- Print nodes in top view of Binary Tree | Set 2
- Print nodes in the Top View of Binary Tree | Set 3
- Print Right View of a Binary Tree
- Print Left View of a Binary Tree
- Print all full nodes in a Binary Tree
- Print all nodes between two given levels in Binary Tree
- Print Levels of all nodes in a Binary Tree
- Print all nodes in a binary tree having K leaves
- Print all even nodes of Binary Search Tree
- Print path between any two nodes in a Binary Tree
- Print leftmost and rightmost nodes of a Binary Tree
- Print Sum and Product of all Non-Leaf nodes in Binary Tree
- Print nodes between two given level numbers of a binary tree
- Print the nodes of binary tree as they become the leaf node
- Print all leaf nodes of a Binary Tree from left to right