Bottom View of a Binary Tree in JavaIn this section, we will learn about the bottom view of a binary tree in Java using different approaches to achieve it. In the bottom 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 bottom. For example, consider the following binary tree. The bottom view is: Note: In the Bottom 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 bottom side of the binary tree should be included in the output.Approach 1: Using QueueWe perform the level order traversal and store the nodes in a queue. We assume that the horizontal distance (horDis) of the root node is 0, moving one step to the level updates the horDis to -1, and moving one step updates the horDis to +1. Note that while doing the level order traversal, we also need to store the horizontal distance along with the nodes, and for doing that, we will use a map, where horDis will be key, and the data of the node will be value. ImplementationLet's see the implementation of the bottom view of a binary tree using a queue. FileName: BottomViewExample.java Output: 10 5 25 14 7 Approach 2: Using HashMap()In the previous approach, we have discussed the bottom view of the tree using a queue. In this approach, we have used Map, where the key is the horizontal distance (horDis) and value is a pair(k, r), where r represents the height of the node and k represent the value of the node. We perform a preorder traversal of the binary tree. If we are observing the value of horizontal distance for the first time for the current node, then we insert it in map. Else, we do a comparison of the current node with the already present node in the map (at a similar horizontal distance). If the height of the current node is greater, we update the map; otherwise, not. ImplementationLet's see the implementation of the bottom view of a binary tree using the HashMap. FileName: BottomViewExample1.java Output: The following are the nodes present in the bottom view of the Binary Tree: 25 14 7 10 5
Next TopicCoercion in Java
|