Right View of a Binary Tree in JavaIn this section, we will learn about the right view of a binary tree in Java and the different approaches to achieve it. In the right 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 right. For the following binary tree: The right view of the above binary tree is: 20 8 5 10 7 Note: In the right view of a Binary Tree, the order in which the nodes are displayed in the output is not relevant. One should care about is that all of the nodes that are visible from the right side of the binary tree should be included in the output.Approach 1: Using RecursionThe approach is to use the recursion to find the right view of the binary tree. A parameter can be passed to all of the recursive calls to find the level of a node. Whenever we come across a node whose level is more than the maximum level found so far, we display that node. It is because it is the last node encountered at this level. Since we have to display the right view of a binary tree, we have to traverse in such a way that the right subtree is visited before the left subtree. ImplementationLet's see the implementation of the right view of a binary tree using recursion. The following code takes the O(n) time to complete its job, and the space complexity of the program is also O(n) because of the stack used in the recursive calls, where n is the total number of nodes present in the binary tree. FileName: RightViewExample.java Output: The following are the nodes present in the right view of the Binary Tree: 20 8 5 10 7 Approach 2: Using Queue()If we observe carefully, we will find that the right view of a binary tree is the last node encountered at every level. Therefore, we can use the queue data structure to traverse each level of the binary tree. At each level, we print only the value of the last node found at each level. ImplementationLet's see the implementation of the right view of a binary tree using the queue. The time complexity of the below program is O(n), where n is the total number of nodes present in the tree. FileName: RightViewExample1.java Output: The following are the nodes present in the right view of the Binary Tree: 20 8 5 10
Next TopicJava Password Generator
