Given a binary tree we have to print top view. We will discuss our approach to solve this problem along with its implementation and code in Java language. We will also analyze the time and space complexity of our implementation. The top view of binary tree means the set of nodes visible when the tree is viewed from top. In other words, a node is included in our top view if it is the topmost node at it’s respective horizontal distance. We calculate the horizontal distance as follows: The Horizontal Distance of Root of tree=0. Horizontal Distance of Left Child=Horizontal Distance of it’s Parent Node – 1. The Horizontal Distance of Right Child=Horizontal Distance of it’s Parent Node + 1. Let us consider binary tree give below: The top view of this tree will give output: 2 1 3 6. Explanation: The nodes are highlighted in the figure above. We put nodes with same horizontal distance together. We start from the root node 1 at level 1 the horizontal distance is 0 at root, then
This website is about programming knowledge. You can call this blog best programming master.