Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • DSA
  • Interview Problems on Tree
  • Practice Tree
  • MCQs on Tree
  • Tutorial on Tree
  • Types of Trees
  • Basic operations
  • Tree Traversal
  • Binary Tree
  • Complete Binary Tree
  • Ternary Tree
  • Binary Search Tree
  • Red-Black Tree
  • AVL Tree
  • Full Binary Tree
  • B-Tree
  • Advantages & Disadvantages
Open In App
Next Article:
Find Minimum Depth of a Binary Tree
Next article icon

Print Right View of a Binary Tree

Last Updated : 26 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report
Try it on GfG Practice
redirect icon

Given a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.

Examples: 

Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree.

2_2


Example 2: The Green colored nodes (1, 3, 4, 5) represents the Right view in the below Binary tree.

Right-view-in-binary-tree-1

Table of Content

  • [Expected Approach - 1] Using Recursion – O(n) Time and O(n) Space
  • [Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space
  • [Expected Approach - 3] Using Morris Traversal – O(n) Time and O(1) Space

[Expected Approach - 1] Using Recursion – O(n) Time and O(n) Space

The idea is to use recursion and keep track of the maximum level also. And traverse the tree in a manner that the right subtree is visited before the left subtree.

Follow the steps below to solve the problem:

  • Perform Postorder traversal to get the rightmost node first.
  • Maintain a variable name maxLevel which will store till which it prints the right view.
  • While traversing the tree in a postorder manner if the current level is greater than maxLevel then print the current node and update maxLevel by the current level.

Below is the implementation of the above approach:

C++
// C++ program to print right view of Binary Tree // using recursion #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node *left, *right;      Node(int x) {         data = x;         left = right = nullptr;     } };  // Helper function for the right view using Recursion void RecursiveRightView(Node* root, int level,                          int& maxLevel, vector<int>& result) {     if (!root) return;      // If current level is more than max level,     // this is the first node of that level     if (level > maxLevel) {         result.push_back(root->data);         maxLevel = level;     }      // Traverse right subtree first, then left subtree     RecursiveRightView(root->right, level + 1,                        maxLevel, result);     RecursiveRightView(root->left, level + 1,                        maxLevel, result); }  // Function to return the right view of the binary tree vector<int> rightView(Node *root) {     vector<int> result;     int maxLevel = -1;      // Start recursion with root at level 0     RecursiveRightView(root, 0, maxLevel, result);          return result; }  void printArray(vector<int>& arr) {     for (int val : arr) {         cout << val << " ";     }     cout << endl; }  int main() {        // Representation of the input tree:     //         1     //        / \     //       2   3     //           / \        //          4   5       Node *root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->right->left = new Node(4);     root->right->right = new Node(5);      vector<int> result = rightView(root);          printArray(result);          return 0; } 
C
// C program to print right view of Binary Tree // using recursion #include <stdio.h> #include <stdlib.h>  struct Node {     int data;     struct Node *left, *right; };  // Helper function for the right view using Recursion void RecursiveRightView(struct Node* root, int level,                 int* maxLevel, int* result, int* index) {     if (!root) return;      // If current level is more than max level,     // this is the first node of that level     if (level > *maxLevel) {         result[(*index)++] = root->data;         *maxLevel = level;     }      // Traverse right subtree first, then      // left subtree     RecursiveRightView(root->right, level + 1,                        maxLevel, result, index);     RecursiveRightView(root->left, level + 1,                         maxLevel, result, index); }  // Function to return the right view of the binary tree void rightView(struct Node* root, int* result, int* size) {     int maxLevel = -1;     int index = 0;      // Start recursion with root at level 0     RecursiveRightView(root, 0, &maxLevel,                        result, &index);          *size = index; }  void printArray(int* arr, int size) {     for (int i = 0; i < size; i++) {         printf("%d ", arr[i]);     }     printf("\n"); }  struct Node* createNode(int x) {     struct Node* newNode        = (struct Node*)malloc(sizeof(struct Node));     newNode->data = x;     newNode->left = newNode->right = NULL;     return newNode; }  int main() {        // Representation of the input tree:     //         1     //        / \     //       2   3     //          / \        //         4   5       struct Node *root = createNode(1);     root->left = createNode(2);     root->right = createNode(3);     root->right->left = createNode(4);     root->right->right = createNode(5);      int result[100];      int size = 0;      rightView(root, result, &size);          printArray(result, size);          return 0; } 
Java
// Java program to print right view of binary tree // using Recursion import java.util.ArrayList;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  // Helper function for the right view using Recursion class GfG {     static void RecursiveRightView(Node root, int level,                    int[] maxLevel, ArrayList<Integer> result) {         if (root == null) return;          // If current level is more than max level,         // this is the first node of that level         if (level > maxLevel[0]) {             result.add(root.data);             maxLevel[0] = level;         }          // Traverse right subtree first, then left subtree         RecursiveRightView(root.right, level + 1,                           maxLevel, result);         RecursiveRightView(root.left, level + 1,                           maxLevel, result);     }      // Function to return the right view of the binary tree     static ArrayList<Integer> rightView(Node root) {         ArrayList<Integer> result = new ArrayList<>();         int[] maxLevel = new int[] {-1};                  // Start recursion with root at level 0         RecursiveRightView(root, 0, maxLevel, result);                  return result;     }      static void printArray(ArrayList<Integer> arr) {         for (int val : arr) {             System.out.print(val + " ");         }         System.out.println();     }      public static void main(String[] args) {                // Representation of the input tree:         //         1         //        / \         //       2   3         //           / \            //          4   5          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.right.left = new Node(4);         root.right.right = new Node(5);          ArrayList<Integer> result = rightView(root);                  printArray(result);     } } 
Python
# Python program to print right view of Binary Tree # using Recursion class Node:     def __init__(self, data):         self.data = data         self.left = None         self.right = None  # Helper function for the right view using Recursion def RecursiveRightView(root, level, maxLevel, result):     if root is None:         return      # If current level is more than max level,     # this is the first node of that level     if level > maxLevel[0]:         result.append(root.data)         maxLevel[0] = level      # Traverse right subtree first, then left subtree     RecursiveRightView(root.right, level + 1,                         maxLevel, result)     RecursiveRightView(root.left, level + 1,                        maxLevel, result)  # Function to return the right view of the binary tree def rightView(root):     result = []     maxLevel = [-1]          # Start recursion with root at level 0     RecursiveRightView(root, 0, maxLevel, result)          return result  def printArray(arr):     for val in arr:         print(val, end=" ")     print()  if __name__ == "__main__":          # Representation of the input tree:     #         1     #        / \     #       2   3     #           / \        #          4   5      root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.right.left = Node(4)     root.right.right = Node(5)      result = rightView(root)          printArray(result) 
C#
// C# program to print right view of binary tree // using Recursion using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = right = null;     } }  class GfG {        // Helper function for the right view using Recursion     static void RecursiveRightView(Node root, int level,                      ref int maxLevel, List<int> result) {         if (root == null) return;          // If current level is more than max level,         // this is the first node of that level         if (level > maxLevel) {             result.Add(root.data);             maxLevel = level;         }          // Traverse right subtree first, then left subtree         RecursiveRightView(root.right, level + 1,                             ref maxLevel, result);         RecursiveRightView(root.left, level + 1,                            ref maxLevel, result);     }      // Function to return the right view of the binary tree     static List<int> rightView(Node root) {         List<int> result = new List<int>();         int maxLevel = -1;          // Start recursion with root at level 0         RecursiveRightView(root, 0, ref maxLevel, result);          return result;     }      static void PrintList(List<int> arr) {         foreach (int val in arr) {             Console.Write(val + " ");         }         Console.WriteLine();     }      static void Main(string[] args) {                // Representation of the input tree:         //         1         //        / \         //       2   3         //           / \            //          4   5          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.right.left = new Node(4);         root.right.right = new Node(5);          List<int> result = rightView(root);                  PrintList(result);     } } 
JavaScript
// JavaScript program to print right view // of binary tree using Recursion class Node {     constructor(data) {         this.data = data;         this.left = null;         this.right = null;     } }  // Helper function for the right view using Recursion function recursiveRightView(root, level, maxLevel, result) {     if (root === null) return;      // If current level is more than max level,     // this is the first node of that level     if (level > maxLevel[0]) {         result.push(root.data);         maxLevel[0] = level;     }      // Traverse right subtree first, then left subtree     recursiveRightView(root.right, level + 1,                                    maxLevel, result);     recursiveRightView(root.left, level + 1,                                     maxLevel, result); }  // Function to return the right view of the binary tree function rightView(root) {     let result = [];     let maxLevel = [-1];      // Start recursion with root at level 0     recursiveRightView(root, 0, maxLevel, result);      return result; }  // Function to print the array function printArray(arr) {     console.log(arr.join(' ')); }  // Representation of the input tree: //         1 //        / \ //       2   3 //           / \    //          4   5  let root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5);  let result = rightView(root);  printArray(result); 

Output
1 3 5  

Time Complexity: O(n), We traverse all nodes of the binary tree exactly once, where n is the number of nodes.
Auxiliary Space: O(h), The space required for the recursion stack will be proportional to the height(h) of the tree, which could be as large as n for a skewed tree.

[Expected Approach – 2] Using Level Order Traversal – O(n) Time and O(n) Space

The idea is to traverse the tree level by level and print the last node at each level (the rightmost node). A simple solution is to do level order traversal and print the last node in every level. Please refer to Right view of Binary Tree using Queue for implementation.

[Expected Approach - 3] Using Morris Traversal – O(n) Time and O(1) Space

The idea is to use Morris Traversal to print the right view of the binary tree by dynamically adjusting the tree's structure during traversal. An empty list is maintained to store the rightmost nodes encountered at each level.

Follow the steps below to implement the idea:

  • Create an empty list view to store the right view nodes and set a variable level to 0 to track the current level of traversal.
  • Use a pointer root to traverse the binary tree. While root is not null, proceed with the traversal.
  • If the current node has a right child, find its inorder predecessor by traversing the leftmost nodes of the right subtree.
  • If the left child of the predecessor is null, add the current node's value to view if it’s the first visit to that level. Then establish a thread from the predecessor to the current node and move to the right child.
  • If the left child of the predecessor is already pointing to the current node (indicating a second visit), remove the thread and move to the left child of the current node.
  • If the current node does not have a right child, add its value to res if it’s the first visit at that level, then move to its left child for further traversal.

Below is the implementation of the above approach.

C++
// C++ program to print right view of Binary // tree using modified Morris Traversal #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node* left;     Node* right;      Node(int x) {         data = x;         left = right = nullptr;     } };  // Function to return the right view of the binary tree vector<int> rightView(Node* root) {          // To store the right view nodes     vector<int> res;            // Current level of traversal     int level = 0;           // Traverse the tree using modified Morris Traversal     while (root) {                  // If the node has a right child,         // find the inorder predecessor         if (root->right) {             Node *pred = root->right;              int backDepth = 1;                           // Find the leftmost node in the right subtree             while (pred->left != nullptr &&                                    pred->left != root) {                 pred = pred->left;                 backDepth++;             }                          // If threading is not yet established             if (pred->left == nullptr) {                                // Add the current node to the view if                  // visiting the level for the first time                 if (res.size() == level) {                     res.push_back(root->data);                 }                                  // Establish the thread and move                  // to the right subtree                 pred->left = root;                 root = root->right;                 level++;               }             else {                                  // Threading was already done                 //(second visit) remove the thread and                  // go to the left subtree                 pred->left = nullptr;                 root = root->left;                 level -= backDepth;               }         }         else {                        // If no right child, process the current              // node and move to the left child             if (res.size() == level) {                 res.push_back(root->data);             }                          root = root->left;             level++;           }     }          // Return the right view nodes     return res; }  void printArray(vector<int>& arr) {      for (int val : arr) {         cout << val << " ";     }          cout << endl; }  int main() {          // Representation of the input tree:     //         1     //        / \     //       2   3     //          / \        //         4   5      Node* root = new Node(1);     root->left = new Node(2);     root->right = new Node(3);     root->right->left = new Node(4);     root->right->right = new Node(5);      vector<int> result = rightView(root);        printArray(result);          return 0; } 
Java
// Java program to print right view of Binary // tree using modified Morris Traversal import java.util.ArrayList;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = right = null;     } }  // Function to return the right view of the binary tree class GfG {          public static ArrayList<Integer> rightView(Node root) {                  // To store the right view nodes         ArrayList<Integer> res = new ArrayList<>();                  // Current level of traversal         int level = 0;          // Traverse the tree using modified          // Morris Traversal         while (root != null) {                          // If the node has a right child,             // find the inorder predecessor             if (root.right != null) {                 Node pred = root.right;                 int backDepth = 1;                  // Find the leftmost node in the                 // right subtree                 while (pred.left != null                                  && pred.left != root) {                     pred = pred.left;                     backDepth++;                 }                  // If threading is not yet established                 if (pred.left == null) {                                          // Add the current node to the view if                      // visiting the level for the first time                     if (res.size() == level) {                         res.add(root.data);                     }                      // Establish the thread and move                      // to the right subtree                     pred.left = root;                     root = root.right;                     level++;                 }                  else {                                          // Threading was already done                      // (second visit) remove the thread                      // and go to the left subtree                     pred.left = null;                     root = root.left;                     level -= backDepth;                 }             }              else {                                  // If no right child, process the current                  // node and move to the left child                 if (res.size() == level) {                     res.add(root.data);                 }                                  root = root.left;                 level++;             }         }          return res;     }      static void printArray(ArrayList<Integer> arr) {         for (int val : arr) {             System.out.print(val + " ");         }         System.out.println();     }      public static void main(String[] args) {                  // Representation of the input tree:         //         1         //        / \         //       2   3         //          / \         //         4   5          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.right.left = new Node(4);         root.right.right = new Node(5);          ArrayList<Integer> result = rightView(root);                  printArray(result);     } } 
Python
# Python program to print right view of Binary Tree # using modified Morris Traversal class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to return the right view of the binary tree def rightView(root):          # To store the right view nodes     res = []          # Current level of traversal     level = 0      # Traverse the tree using modified Morris Traversal     while root:                  # If the node has a right child,         # find the inorder predecessor         if root.right:             pred = root.right             backDepth = 1              # Find the leftmost node in the right subtree             while pred.left and pred.left != root:                 pred = pred.left                 backDepth += 1              # If threading is not yet established             if pred.left is None:                                  # Add the current node to the view if                  # visiting the level for the first time                 if len(res) == level:                     res.append(root.data)                  # Establish the thread and move                  # to the right subtree                 pred.left = root                 root = root.right                 level += 1             else:                                  # Threading was already done                  # (second visit) remove the thread                 # and go to the left subtree                 pred.left = None                 root = root.left                 level -= backDepth         else:                          # If no right child, process the current              # node and move to the left child             if len(res) == level:                 res.append(root.data)              root = root.left             level += 1          # Return the right view nodes     return res  def printArray(arr):     for val in arr:         print(val, end=" ")     print()   if __name__ == "__main__":        # Representation of the input tree:     #         1     #        / \     #       2   3     #          / \     #         4   5      root = Node(1)     root.left = Node(2)     root.right = Node(3)     root.right.left = Node(4)     root.right.right = Node(5)      result = rightView(root)          printArray(result) 
C#
// C# program to print right view of Binary Tree // using modified Morris Traversal using System; using System.Collections.Generic;  class Node {     public int data;     public Node left, right;      public Node(int x) {         data = x;         left = right = null;     } }  // Function to return the right view of the binary tree class GfG {          static List<int> rightView(Node root) {                  // To store the right view nodes         List<int> res = new List<int>();                  // Current level of traversal         int level = 0;          // Traverse the tree using modified          // Morris Traversal         while (root != null) {                          // If the node has a right child,             // find the inorder predecessor             if (root.right != null) {                 Node pred = root.right;                 int backDepth = 1;                  // Find the leftmost node in the                  // right subtree                 while (pred.left != null                                  && pred.left != root) {                     pred = pred.left;                     backDepth++;                 }                  // If threading is not yet established                 if (pred.left == null) {                                          // Add the current node to the view if                      // visiting the level for the first time                     if (res.Count == level) {                         res.Add(root.data);                     }                      // Establish the thread and move                      // to the right subtree                     pred.left = root;                     root = root.right;                     level++;                 }                  else {                                          // Threading was already done                      // (second visit) remove the thread                     // and go to the left subtree                     pred.left = null;                     root = root.left;                     level -= backDepth;                 }             }              else {                                  // If no right child, process the current                  // node and move to the left child                 if (res.Count == level) {                     res.Add(root.data);                 }                                  root = root.left;                 level++;             }         }          // Return the right view nodes         return res;     }  	static void printArray(List<int> arr) {         foreach (int val in arr) {             Console.Write(val + " ");         }         Console.WriteLine();     }     static void Main(string[] args) {                  // Representation of the input tree:         //         1         //        / \         //       2   3         //          / \         //         4   5          Node root = new Node(1);         root.left = new Node(2);         root.right = new Node(3);         root.right.left = new Node(4);         root.right.right = new Node(5);          List<int> result = rightView(root);                  printArray(result);     } } 
JavaScript
// JavaScript program to print right view of Binary // tree using modified Morris Traversal  class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to return the right view of the binary tree function rightView(root) {          // To store the right view nodes     const res = [];          // Current level of traversal     let level = 0;      // Traverse the tree using modified Morris Traversal     while (root) {                  // If the node has a right child,         // find the inorder predecessor         if (root.right) {             let pred = root.right;             let backDepth = 1;              // Find the leftmost node in the right subtree             while (pred.left && pred.left !== root) {                 pred = pred.left;                 backDepth++;             }              // If threading is not yet established             if (pred.left === null) {                                  // Add the current node to the view if                  // visiting the level for the first time                 if (res.length === level) {                     res.push(root.data);                 }                  // Establish the thread and move                  // to the right subtree                 pred.left = root;                 root = root.right;                 level++;             }              else {                                  // Threading was already done (second visit)                 // remove the thread and go to the left subtree                 pred.left = null;                 root = root.left;                 level -= backDepth;             }         }          else {                          // If no right child, process the current              // node and move to the left child             if (res.length === level) {                 res.push(root.data);             }                          root = root.left;             level++;         }     }          // Return the right view nodes     return res; }  function printArray(arr) {     console.log(arr.join(' ')); }  // Representation of the input tree: //         1 //        / \ //       2   3 //          / \ //         4   5  const root = new Node(1); root.left = new Node(2); root.right = new Node(3); root.right.left = new Node(4); root.right.right = new Node(5);  const result = rightView(root); printArray(result); 

Output
1 3 5  

Time Complexity:O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly twice (once when we find its inorder predecessor, and once when we visit it from its inorder predecessor).
Auxiliary Space: O(1), because we only use a constant amount of extra space for the pointers. We do not use any additional data structures or recursive function calls that would increase the space complexity.


Next Article
Find Minimum Depth of a Binary Tree

K

kartik
Improve
Article Tags :
  • Tree
  • DSA
  • Amazon
  • Adobe
  • Snapdeal
  • Accolite
  • MakeMyTrip
  • tree-view
Practice Tags :
  • Accolite
  • Adobe
  • Amazon
  • MakeMyTrip
  • Snapdeal
  • Tree

Similar Reads

    Queue Data Structure
    A Queue Data Structure is a fundamental concept in computer science used for storing and managing data in a specific order. It follows the principle of "First in, First out" (FIFO), where the first element added to the queue is the first one to be removed. It is used as a buffer in computer systems
    2 min read
    Introduction to Queue Data Structure
    Queue is a linear data structure that follows FIFO (First In First Out) Principle, so the first element inserted is the first to be popped out. FIFO Principle in Queue:FIFO Principle states that the first element added to the Queue will be the first one to be removed or processed. So, Queue is like
    5 min read
    Introduction and Array Implementation of Queue
    Similar to Stack, Queue is a linear data structure that follows a particular order in which the operations are performed for storing data. The order is First In First Out (FIFO). One can imagine a queue as a line of people waiting to receive something in sequential order which starts from the beginn
    2 min read
    Queue - Linked List Implementation
    In this article, the Linked List implementation of the queue data structure is discussed and implemented. Print '-1' if the queue is empty.Approach: To solve the problem follow the below idea:we maintain two pointers, front and rear. The front points to the first item of the queue and rear points to
    8 min read
    Applications, Advantages and Disadvantages of Queue
    A Queue is a linear data structure. This data structure follows a particular order in which the operations are performed. The order is First In First Out (FIFO). It means that the element that is inserted first in the queue will come out first and the element that is inserted last will come out last
    5 min read
    Different Types of Queues and its Applications
    Introduction : A Queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. In this article, the diff
    8 min read

    Queue implementation in different languages

    Queue in C++ STL
    In C++, queue container follows the FIFO (First In First Out) order of insertion and deletion. According to it, the elements that are inserted first should be removed first. This is possible by inserting elements at one end (called back) and deleting them from the other end (called front) of the dat
    4 min read
    Queue Interface In Java
    The Queue Interface is a part of java.util package and extends the Collection interface. It stores and processes the data in order means elements are inserted at the end and removed from the front. Key Features:Most implementations, like PriorityQueue, do not allow null elements.Implementation Class
    12 min read
    Queue in Python
    Like a stack, the queue is a linear data structure that stores items in a First In First Out (FIFO) manner. With a queue, the least recently added item is removed first. A good example of a queue is any queue of consumers for a resource where the consumer that came first is served first. Operations
    6 min read
    C# Queue with Examples
    A Queue in C# is a collection that follows the First-In-First-Out (FIFO) principle which means elements are processed in the same order they are added. It is a part of the System.Collections namespace for non-generic queues and System.Collections.Generic namespace for generic queues.Key Features:FIF
    6 min read
    Implementation of Queue in Javascript
    A Queue is a linear data structure that follows the FIFO (First In, First Out) principle. Elements are inserted at the rear and removed from the front.Queue Operationsenqueue(item) - Adds an element to the end of the queue.dequeue() - Removes and returns the first element from the queue.peek() - Ret
    7 min read
    Queue in Go Language
    A queue is a linear structure that follows a particular order in which the operations are performed. The order is First In First Out (FIFO). Now if you are familiar with other programming languages like C++, Java, and Python then there are inbuilt queue libraries that can be used for the implementat
    4 min read
    Queue in Scala
    A queue is a first-in, first-out (FIFO) data structure. Scala offers both an immutable queue and a mutable queue. A mutable queue can be updated or extended in place. It means one can change, add, or remove elements of a queue as a side effect. Immutable queue, by contrast, never change. In Scala, Q
    3 min read

    Some question related to Queue implementation

    Implementation of Deque using doubly linked list
    A Deque (Double-Ended Queue) is a data structure that allows adding and removing elements from both the front and rear ends. Using a doubly linked list to implement a deque makes these operations very efficient, as each node in the list has pointers to both the previous and next nodes. This means we
    9 min read
    Queue using Stacks
    Given a stack that supports push and pop operations, your task is to implement a queue using one or more instances of that stack along with its operations.Table of ContentBy Making Enqueue Operation CostlyBy Making Dequeue Operation Costly Queue Implementation Using One Stack and RecursionBy Making
    11 min read
    implement k Queues in a single array
    Given an array of size n, the task is to implement k queues using the array.enqueue(qn, x) : Adds the element x into the queue number qn dequeue(qn, x) : Removes the front element from queue number qn isFull(qn) : Checks if the queue number qn is fullisEmpty(qn) : Checks if the queue number qn is em
    15+ min read
    LRU Cache - Complete Tutorial
    What is LRU Cache? Cache replacement algorithms are efficiently designed to replace the cache when the space is full. The Least Recently Used (LRU) is one of those algorithms. As the name suggests when the cache memory is full, LRU picks the data that is least recently used and removes it in order t
    8 min read

    Easy problems on Queue

    Detect cycle in an undirected graph using BFS
    Given an undirected graph, the task is to determine if cycle is present in it or not.Examples:Input: V = 5, edges[][] = [[0, 1], [0, 2], [0, 3], [1, 2], [3, 4]]Undirected Graph with 5 NodeOutput: trueExplanation: The diagram clearly shows a cycle 0 → 2 → 1 → 0.Input: V = 4, edges[][] = [[0, 1], [1,
    6 min read
    Breadth First Search or BFS for a Graph
    Given a undirected graph represented by an adjacency list adj, where each adj[i] represents the list of vertices connected to vertex i. Perform a Breadth First Search (BFS) traversal starting from vertex 0, visiting vertices from left to right according to the adjacency list, and return a list conta
    15+ min read
    Traversing directory in Java using BFS
    Given a directory, print all files and folders present in directory tree rooted with given directory. We can iteratively traverse directory in BFS using below steps. We create an empty queue and we first enqueue given directory path. We run a loop while queue is not empty. We dequeue an item from qu
    2 min read
    Vertical Traversal of a Binary Tree
    Given a Binary Tree, the task is to find its vertical traversal starting from the leftmost level to the rightmost level. If multiple nodes pass through a vertical line, they should be printed as they appear in the level order traversal of the tree.Examples: Input:Output: [[4], [2], [1, 5, 6], [3, 8]
    10 min read
    Print Right View of a Binary Tree
    Given a Binary Tree, the task is to print the Right view of it. The right view of a Binary Tree is a set of rightmost nodes for every level.Examples: Example 1: The Green colored nodes (1, 3, 5) represents the Right view in the below Binary tree. Example 2: The Green colored nodes (1, 3, 4, 5) repre
    15+ min read
    Find Minimum Depth of a Binary Tree
    Given a binary tree, find its minimum depth. The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node. For example, minimum depth of below Binary Tree is 2. Note that the path must end on a leaf node. For example, the minimum depth of below Bi
    15 min read
    Check whether a given graph is Bipartite or not
    Given a graph with V vertices numbered from 0 to V-1 and a list of edges, determine whether the graph is bipartite or not.Note: A bipartite graph is a type of graph where the set of vertices can be divided into two disjoint sets, say U and V, such that every edge connects a vertex in U to a vertex i
    8 min read

    Intermediate problems on Queue

    Flatten a multilevel linked list using level order traversal
    Given a linked list where in addition to the next pointer, each node has a child pointer, which may or may not point to a separate list. These child lists may have one or more children of their own to produce a multilevel linked list. Given the head of the first level of the list. The task is to fla
    9 min read
    Level with maximum number of nodes
    Given a binary tree, the task is to find the level in a binary tree that has the maximum number of nodes. Note: The root is at level 0.Examples: Input: Binary Tree Output : 2Explanation: Input: Binary tree Output:1Explanation Using Breadth First Search - O(n) time and O(n) spaceThe idea is to traver
    12 min read
    Find if there is a path between two vertices in a directed graph
    Given a Directed Graph and two vertices src and dest, check whether there is a path from src to dest.Example: Consider the following Graph: adj[][] = [ [], [0, 2], [0, 3], [], [2] ]Input : src = 1, dest = 3Output: YesExplanation: There is a path from 1 to 3, 1 -> 2 -> 3Input : src = 0, dest =
    11 min read
    All nodes between two given levels in Binary Tree
    Given a binary tree, the task is to print all nodes between two given levels in a binary tree. Print the nodes level-wise, i.e., the nodes for any level should be printed from left to right. Note: The levels are 1-indexed, i.e., root node is at level 1.Example: Input: Binary tree, l = 2, h = 3Output
    8 min read
    Find next right node of a given key
    Given a Binary tree and a key in the binary tree, find the node right to the given key. If there is no node on right side, then return NULL. Expected time complexity is O(n) where n is the number of nodes in the given binary tree.Example:Input: root = [10 2 6 8 4 N 5] and key = 2Output: 6Explanation
    15+ min read
    Minimum steps to reach target by a Knight | Set 1
    Given a square chessboard of n x n size, the position of the Knight and the position of a target are given. We need to find out the minimum steps a Knight will take to reach the target position.Examples: Input: KnightknightPosition: (1, 3) , targetPosition: (5, 0)Output: 3Explanation: In above diagr
    9 min read
    Islands in a graph using BFS
    Given an n x m grid of 'W' (Water) and 'L' (Land), the task is to count the number of islands. An island is a group of adjacent 'L' cells connected horizontally, vertically, or diagonally, and it is surrounded by water or the grid boundary. The goal is to determine how many distinct islands exist in
    15+ min read
    Level order traversal line by line (Using One Queue)
    Given a Binary Tree, the task is to print the nodes level-wise, each level on a new line.Example:Input:Output:12 34 5Table of Content[Expected Approach – 1] Using Queue with delimiter – O(n) Time and O(n) Space[Expected Approach – 2] Using Queue without delimiter – O(n) Time and O(n) Space[Expected
    12 min read
    First non-repeating character in a stream
    Given an input stream s consisting solely of lowercase letters, you are required to identify which character has appeared only once in the stream up to each point. If there are multiple characters that have appeared only once, return the one that first appeared. If no character has appeared only onc
    15+ min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences