Right view of Binary Tree using Queue

10 Jun, 2022
Given a Binary Tree, print Right view of it. Right view of a Binary Tree is set of nodes visible when tree is visited from Right side. Examples:  
Input : 
              10
            /     \
          2         3
        /   \    /    \
       7     8  12     15
                      /
                    14
Output : 10 3 15 14
The output nodes are the rightmost
nodes of their respective levels.
 
We have already discussed recursive solution for right view. In this post, level order traversal based solution is discussed. If we observe carefully, we will see that our main task is to print the right most node of every level. So, we will do a level order traversal on the tree and print the rightmost node at every level.Below is the implementation of above approach:  
C++
Java
Python3
C#
Javascript
// C++ program to print right view of// Binary Tree #include<bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node{    int data;    struct Node *left, *right;}; // Utility function to create a new tree nodeNode* newNode(int data){    Node *temp = new Node;    temp->data = data;    temp->left = temp->right = NULL;    return temp;} // function to print right view of// binary treevoid printRightView(Node* root){    if (!root)        return;     queue<Node*> q;    q.push(root);     while (!q.empty())    {           // number of nodes at current level        int n = q.size();                 // Traverse all nodes of current level        for(int i = 1; i <= n; i++)        {            Node* temp = q.front();            q.pop();                             // Print the right most element            // at the level            if (i == n)                cout<<temp->data<<" ";                         // Add left node to queue            if (temp->left != NULL)                q.push(temp->left);             // Add right node to queue            if (temp->right != NULL)                q.push(temp->right);        }    }}    // Driver program to test above functionsint main(){    // Let's construct the tree as    // shown in example     Node* root = newNode(10);    root->left = newNode(2);    root->right = newNode(3);    root->left->left = newNode(7);    root->left->right = newNode(8);    root->right->right = newNode(15);    root->right->left = newNode(12);    root->right->right->left = newNode(14);     printRightView(root);}
// Java program to print right view of Binary// Treeimport java.util.*; public class PrintRightView{      // Binary tree node    private static class Node    {        int data;        Node left, right;         public Node(int data) {            this.data = data;            this.left = null;            this.right = null;        }    }         // function to print right view of binary tree    private static void printRightView(Node root)    {        if (root == null)            return;                     Queue<Node> queue = new LinkedList<>();        queue.add(root);                 while (!queue.isEmpty())        {              // number of nodes at current level            int n = queue.size();                         // Traverse all nodes of current level            for (int i = 1; i <= n; i++) {                Node temp = queue.poll();                                 // Print the right most element at                // the level                if (i == n)                    System.out.print(temp.data + " ");                                 // Add left node to queue                if (temp.left != null)                    queue.add(temp.left);                                     // Add right node to queue                if (temp.right != null)                    queue.add(temp.right);            }        }    }     // Driver code    public static void main(String[] args)    {        // construct binary tree as shown in        // above diagram        Node root = new Node(10);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(7);        root.left.right = new Node(8);        root.right.right = new Node(15);        root.right.left = new Node(12);        root.right.right.left = new Node(14);                 printRightView(root);    }}
# Python3 program to print right view of# Binary Tree # Binary Tree Node""" utility that allocates a newNodewith the given key """class newNode:     # Construct to create a newNode    def __init__(self, key):        self.data = key        self.left = None        self.right = None        self.hd = 0 # function to print right view of# binary treedef printRightView(root):     if (not root):        return     q = []    q.append(root)     while (len(q)):                 # number of nodes at current level        n = len(q)                 # Traverse all nodes of current level        for i in range(1, n + 1):                    temp = q[0]            q.pop(0)                             # Print the right most element            # at the level            if (i == n) :                print(temp.data, end = " " )                         # Add left node to queue            if (temp.left != None) :                q.append(temp.left)             # Add right node to queue            if (temp.right != None) :                q.append(temp.right) # Driver Codeif __name__ == '__main__':     root = newNode(10)    root.left = newNode(2)    root.right = newNode(3)    root.left.left = newNode(7)    root.left.right = newNode(8)    root.right.right = newNode(15)    root.right.left = newNode(12)    root.right.right.left = newNode(14)    printRightView(root) # This code is contributed by# Shubham Singh(SHUBHAMSINGH10)
// C# program to print right view// of Binary Treeusing System;using System.Collections.Generic; public class PrintRightView{    // Binary tree node    private class Node    {        public int data;        public Node left, right;         public Node(int data)        {            this.data = data;            this.left = null;            this.right = null;        }    }         // function to print right view of binary tree    private static void printRightView(Node root)    {        if (root == null)            return;                     Queue<Node> queue = new Queue<Node>();        queue.Enqueue(root);                 while (queue.Count != 0)        {            // number of nodes at current level            int n = queue.Count;                         // Traverse all nodes of current level            for (int i = 1; i <= n; i++)            {                Node temp = queue.Dequeue();                                 // Print the right most element at                // the level                if (i == n)                    Console.Write(temp.data + " ");                                 // Add left node to queue                if (temp.left != null)                    queue.Enqueue(temp.left);                                     // Add right node to queue                if (temp.right != null)                    queue.Enqueue(temp.right);            }        }    }     // Driver code    public static void Main(String[] args)    {        // construct binary tree as shown in        // above diagram        Node root = new Node(10);        root.left = new Node(2);        root.right = new Node(3);        root.left.left = new Node(7);        root.left.right = new Node(8);        root.right.right = new Node(15);        root.right.left = new Node(12);        root.right.right.left = new Node(14);        printRightView(root);    }} // This code is contributed 29AjayKumar
<script>   // JavaScript program to print right view// of Binary Tree// Binary tree nodeclass Node{    constructor(data)    {        this.data = data;        this.left = null;        this.right = null;    }} // function to print right view of binary treefunction printRightView(root){    if (root == null)        return;             var queue = [];    queue.push(root);         while (queue.length != 0)    {        // number of nodes at current level        var n = queue.length;                 // Traverse all nodes of current level        for (var i = 1; i <= n; i++)        {            var temp = queue.shift();                         // Print the right most element at            // the level            if (i == n)                document.write(temp.data + " ");                         // Add left node to queue            if (temp.left != null)                queue.push(temp.left);                             // Add right node to queue            if (temp.right != null)                queue.push(temp.right);        }    }}// Driver code// construct binary tree as shown in// above diagramvar root = new Node(10);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(7);root.left.right = new Node(8);root.right.right = new Node(15);root.right.left = new Node(12);root.right.right.left = new Node(14);printRightView(root); </script>
Output:  
10 3 15 14
Time Complexity: O( n ), where n is the number of nodes in the binary tree. 
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
default, selected
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
Auxiliary Space: O( n ) for Queue Data Structure  
Right view of Binary Tree using Queue | GeeksforGeeks - YouTubeGeeksforGeeks530K subscribersRight view of Binary Tree using Queue | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 4:49•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=RUezU6R4JVI" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
This article is contributed by Bibhas Abhishek. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. 
 
SHUBHAMSINGH10
29AjayKumar
rrrtnx
prasanna1995
polymatir3j
tree-traversal
tree-view
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Data Structures
Introduction to Tree Data Structure
Inorder Tree Traversal without Recursion
What is Data Structure: Types, Classifications and Applications
Binary Tree | Set 3 (Types of Binary Tree)
A program to check if a binary tree is BST or not
Lowest Common Ancestor in a Binary Tree | Set 1
Binary Tree | Set 2 (Properties)
Diameter of a Binary Tree