Top View of a Binary Tree in JavaIn this section, we will learn about the top view of a binary tree in Java and the different approaches to achieve it. In the top view of a binary tree, we print only those nodes of the binary tree that are visible when the binary tree is viewed from the top. For example, consider the following binary tree. The top view of the above binary tree is: For the following binary tree: The top view of the above binary tree is: Note: In the top view of a binary tree, the order in which the nodes are displayed in the output is not relevant. All one should care about is that all of the nodes that are visible from the top side of the binary tree should be included in the output.Approach 1: Using QueueIn this approach, we need to group the nodes whose horizontal distance is the same by taking the root node as the reference. We perform a level order traversal of the tree using a queue so that the topmost nodes are visited before the nodes that are lying below it. Hashing technique is used to identify whether a given horizontal distance is seen or not. ImplementationLet's see the implementation of the top view of a binary tree using the horizontal distance approach. FileName: TopViewExample.java Output: The following are the nodes present in the top view of the Binary Tree 7 4 3 2 1 Approach 2: Using Two VariablesIn the previous approach, we have discussed the top view of the tree using a queue. In this approach, we will be using two variables instead of a queue. One variable is used to identify the depth of a node taking the root node as a reference, and another for finding the vertical distance from the root node. For indexing, we use vertical distancing. If any other node with the same vertical distance is visited again, then we have to check whether the depth of the new node is higher or lower as compared to the current node. We do the replacement when the depth is lower of the new node. ImplementationLet's see the implementation of the top view of a binary tree using the two variables. FileName: TopViewExample1.java Output: The following are the nodes present in the top view of the Binary Tree 7 4 3 2 1
Next TopicTribonacci Series in Java
|