Find next right node of a given key
Last Updated :
08 May, 2025
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 = 2

Output: 6
Explanation: We can see in the above tree
that the next right node of 2 is 6.
Approach
The idea is to do level order traversal of given Binary Tree. When we find the given key, we just check if the next node in level order traversal is of same level, if yes, we return the next node, otherwise return NULL.
C++
/* Program to find next right of a given key */
#include <iostream>
#include <queue>
using namespace std;
// A Binary Tree Node
struct node
{
struct node *left, *right;
int key;
};
// Method to find next right of given key k, it returns NULL if k is
// not present in tree or k is the rightmost node of its level
node* nextRight(node *root, int k)
{
// Base Case
if (root == NULL)
return 0;
// Create an empty queue for level order traversal
queue<node *> qn; // A queue to store node addresses
queue<int> ql; // Another queue to store node levels
int level = 0; // Initialize level as 0
// Enqueue Root and its level
qn.push(root);
ql.push(level);
// A standard BFS loop
while (qn.size())
{
// dequeue an node from qn and its level from ql
node *node = qn.front();
level = ql.front();
qn.pop();
ql.pop();
// If the dequeued node has the given key k
if (node->key == k)
{
// If there are no more items in queue or given node is
// the rightmost node of its level, then return NULL
if (ql.size() == 0 || ql.front() != level)
return NULL;
// Otherwise return next node from queue of nodes
return qn.front();
}
// Standard BFS steps: enqueue children of this node
if (node->left != NULL)
{
qn.push(node->left);
ql.push(level+1);
}
if (node->right != NULL)
{
qn.push(node->right);
ql.push(level+1);
}
}
// We reach here if given key x doesn't exist in tree
return NULL;
}
// Utility function to create a new tree node
node* newNode(int key)
{
node *temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to test above functions
void test(node *root, int k)
{
node *nr = nextRight(root, k);
if (nr != NULL)
cout << "Next Right of " << k << " is " << nr->key << endl;
else
cout << "No next right node found for " << k << endl;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
node *root = newNode(10);
root->left = newNode(2);
root->right = newNode(6);
root->right->right = newNode(5);
root->left->left = newNode(8);
root->left->right = newNode(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
return 0;
}
Java
// Java program to find next right of a given key
import java.util.LinkedList;
import java.util.Queue;
// A binary tree node
class Node
{
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree
{
Node root;
// Method to find next right of given key k, it returns NULL if k is
// not present in tree or k is the rightmost node of its level
Node nextRight(Node first, int k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for level order traversal
// A queue to store node addresses
Queue<Node> qn = new LinkedList<Node>();
// Another queue to store node levels
Queue<Integer> ql = new LinkedList<Integer>();
int level = 0; // Initialize level as 0
// Enqueue Root and its level
qn.add(first);
ql.add(level);
// A standard BFS loop
while (qn.size() != 0)
{
// dequeue an node from qn and its level from ql
Node node = qn.peek();
level = ql.peek();
qn.remove();
ql.remove();
// If the dequeued node has the given key k
if (node.data == k)
{
// If there are no more items in queue or given node is
// the rightmost node of its level, then return NULL
if (ql.size() == 0 || ql.peek() != level)
return null;
// Otherwise return next node from queue of nodes
return qn.peek();
}
// Standard BFS steps: enqueue children of this node
if (node.left != null)
{
qn.add(node.left);
ql.add(level + 1);
}
if (node.right != null)
{
qn.add(node.right);
ql.add(level + 1);
}
}
// We reach here if given key x doesn't exist in tree
return null;
}
// A utility function to test above functions
void test(Node node, int k)
{
Node nr = nextRight(root, k);
if (nr != null)
System.out.println("Next Right of " + k + " is " + nr.data);
else
System.out.println("No next right node found for " + k);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(2);
tree.root.right = new Node(6);
tree.root.right.right = new Node(5);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(4);
tree.test(tree.root, 10);
tree.test(tree.root, 2);
tree.test(tree.root, 6);
tree.test(tree.root, 5);
tree.test(tree.root, 8);
tree.test(tree.root, 4);
}
}
// This code has been contributed by Mayank Jaiswal
Python
# Python program to find next right node of given key
# A Binary Tree Node
class Node:
# Constructor to create a new node
def __init__(self, key):
self.key = key
self.left = None
self.right = None
# Method to find next right of a given key k, it returns
# None if k is not present in tree or k is the rightmost
# node of its level
def nextRight(root, k):
# Base Case
if root is None:
return 0
# Create an empty queue for level order traversal
qn = [] # A queue to store node addresses
q1 = [] # Another queue to store node levels
level = 0
# Enqueue root and its level
qn.append(root)
q1.append(level)
# Standard BFS loop
while(len(qn) > 0):
# Dequeue an node from qn and its level from q1
node = qn.pop(0)
level = q1.pop(0)
# If the dequeued node has the given key k
if node.key == k :
# If there are no more items in queue or given
# node is the rightmost node of its level,
# then return None
if (len(q1) == 0 or q1[0] != level):
return None
# Otherwise return next node from queue of nodes
return qn[0]
# Standard BFS steps: enqueue children of this node
if node.left is not None:
qn.append(node.left)
q1.append(level+1)
if node.right is not None:
qn.append(node.right)
q1.append(level+1)
# We reach here if given key x doesn't exist in tree
return None
def test(root, k):
nr = nextRight(root, k)
if nr is not None:
print ("Next Right of " + str(k) + " is " + str(nr.key))
else:
print ("No next right node found for " + str(k))
# Driver program to test above function
root = Node(10)
root.left = Node(2)
root.right = Node(6)
root.right.right = Node(5)
root.left.left = Node(8)
root.left.right = Node(4)
test(root, 10)
test(root, 2)
test(root, 6)
test(root, 5)
test(root, 8)
test(root, 4)
# This code is contributed by Nikhil Kumar Singh(nickzuck_007)
C#
// C# program to find next right of a given key
using System;
using System.Collections.Generic;
// A binary tree node
public class Node
{
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
public class BinaryTree
{
Node root;
// Method to find next right of given
// key k, it returns NULL if k is
// not present in tree or k is the
// rightmost node of its level
Node nextRight(Node first, int k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for
// level order traversal
// A queue to store node addresses
Queue<Node> qn = new Queue<Node>();
// Another queue to store node levels
Queue<int> ql = new Queue<int>();
int level = 0; // Initialize level as 0
// Enqueue Root and its level
qn.Enqueue(first);
ql.Enqueue(level);
// A standard BFS loop
while (qn.Count != 0)
{
// dequeue an node from
// qn and its level from ql
Node node = qn.Peek();
level = ql.Peek();
qn.Dequeue();
ql.Dequeue();
// If the dequeued node has the given key k
if (node.data == k)
{
// If there are no more items
// in queue or given node is
// the rightmost node of its
// level, then return NULL
if (ql.Count == 0 || ql.Peek() != level)
return null;
// Otherwise return next
// node from queue of nodes
return qn.Peek();
}
// Standard BFS steps: enqueue
// children of this node
if (node.left != null)
{
qn.Enqueue(node.left);
ql.Enqueue(level + 1);
}
if (node.right != null)
{
qn.Enqueue(node.right);
ql.Enqueue(level + 1);
}
}
// We reach here if given
// key x doesn't exist in tree
return null;
}
// A utility function to test above functions
void test(Node node, int k)
{
Node nr = nextRight(root, k);
if (nr != null)
Console.WriteLine("Next Right of " +
k + " is " + nr.data);
else
Console.WriteLine("No next right node found for " + k);
}
// Driver code
public static void Main(String []args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(2);
tree.root.right = new Node(6);
tree.root.right.right = new Node(5);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(4);
tree.test(tree.root, 10);
tree.test(tree.root, 2);
tree.test(tree.root, 6);
tree.test(tree.root, 5);
tree.test(tree.root, 8);
tree.test(tree.root, 4);
}
}
// This code has been contributed
// by 29AjayKumar
JavaScript
<script>
// Javascript program to find next right of a given key
// A binary tree node
class Node
{
constructor(item)
{
this.data = item;
this.left = this.right = null;
}
}
let root;
// Method to find next right of given key k,
// it returns NULL if k is not present in
// tree or k is the rightmost node of its level
function nextRight(first, k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for level
// order traversal. A queue to
// store node addresses
let qn = [];
// Another queue to store node levels
let ql = [];
// Initialize level as 0
let level = 0;
// Enqueue Root and its level
qn.push(first);
ql.push(level);
// A standard BFS loop
while (qn.length != 0)
{
// dequeue an node from qn and its level from ql
let node = qn[0];
level = ql[0];
qn.shift();
ql.shift();
// If the dequeued node has the given key k
if (node.data == k)
{
// If there are no more items in queue
// or given node is the rightmost node
// of its level, then return NULL
if (ql.length == 0 || ql[0] != level)
return null;
// Otherwise return next node
// from queue of nodes
return qn[0];
}
// Standard BFS steps: enqueue
// children of this node
if (node.left != null)
{
qn.push(node.left);
ql.push(level + 1);
}
if (node.right != null)
{
qn.push(node.right);
ql.push(level + 1);
}
}
// We reach here if given key
// x doesn't exist in tree
return null;
}
// A utility function to test above functions
function test(node, k)
{
let nr = nextRight(root, k);
if (nr != null)
document.write("Next Right of " + k +
" is " + nr.data + "<br>");
else
document.write("No next right node found for " +
k + "<br>");
}
// Driver code
root = new Node(10);
root.left = new Node(2);
root.right = new Node(6);
root.right.right = new Node(5);
root.left.left = new Node(8);
root.left.right = new Node(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
// This code is contributed by rag2127
</script>
OutputNo next right node found for 10
Next Right of 2 is 6
No next right node found for 6
No next right node found for 5
Next Right of 8 is 4
Next Right of 4 is 5
Time Complexity: The above code is a simple BFS traversal code which visits every enqueue and dequeues a node at most once. Therefore, the time complexity is O(n) where n is the number of nodes in the given binary tree.
Auxiliary Space: O(n)
Efficient Approach :
The idea is to use the level order traversal of a binary tree discussed in the 2nd approach of this post.
If we do the level order traversal in the above fashion then while processing the nodes of a level we can check if it is the last element of that level or not. If it is not the last element of it's level then there will definitely be an element next to it. See the below C++ code to understand the approach clearly.
Implementation:
C++
/* Program to find next right of a given key */
#include <iostream>
#include <queue>
using namespace std;
// A Binary Tree Node
struct node {
struct node *left, *right;
int key;
};
// Method to find next right of given key k, it returns NULL
// if k is not present in tree or k is the rightmost node of
// its level
node* nextRight(node* root, int key)
{
// Base case
if (root == NULL)
return NULL;
// variable to store the result
node* res = NULL;
// queue q to store the nodes of the tree
queue<node*> q;
// push the root in the queue
q.push(root);
// A modified BFS loop
while (!q.empty()) {
// Get the count of the elements in the queue, this
// is also the count of elements present at the
// current level
int n = q.size();
// loop through the elements of the current level
for (int i = 0; i < n; i++) {
// take out the front of the queue
node* temp = q.front();
q.pop();
// if the key is found we check if there is any
// element next to it and return the answer
// accordingally
if (temp->key == key) {
if (i != n - 1)
return q.front();
else
return NULL;
}
// while the current level elements are
// processed we push their children into the
// queue
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
}
// If we reach here, it means the element was not found
// and thus no next element will be there
return NULL;
}
// Utility function to create a new tree node
node* newNode(int key)
{
node* temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
// A utility function to test above functions
void test(node* root, int k)
{
node* nr = nextRight(root, k);
if (nr != NULL)
cout << "Next Right of " << k << " is " << nr->key
<< endl;
else
cout << "No next right node found for " << k
<< endl;
}
// Driver program to test above functions
int main()
{
// Let us create binary tree given in the above example
node* root = newNode(10);
root->left = newNode(2);
root->right = newNode(6);
root->right->right = newNode(5);
root->left->left = newNode(8);
root->left->right = newNode(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
return 0;
}
// This code is contributed by Abhijeet Kumar(abhijeet19403)
Java
// Java program to find next right of a given key
import java.util.LinkedList;
import java.util.Queue;
// A binary tree node
class Node {
int data;
Node left, right;
Node(int item)
{
data = item;
left = right = null;
}
}
class BinaryTree {
Node root;
// Method to find next right of given key k, it returns
// NULL if k is not present in tree or k is the
// rightmost node of its level
Node nextRight(Node first, int k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for level order traversal
// A queue to store node addresses
Node res = null;
Queue<Node> q = new LinkedList<Node>();
// Enqueue Root and its level
q.add(first);
// A standard BFS loop
while (q.size() != 0) {
// Get the count of the elements in the queue,
// this
// is also the count of elements present at the
// current level
int n = q.size();
// loop through the elements of the current
// level
for (int i = 0; i < n; i++) {
Node temp = q.peek();
q.remove();
// if the key is found we check if there is
// any
// element next to it and return the answer
// accordingally
if (temp.data == k) {
if (i != n - 1) {
return q.peek();
}
else
return null;
}
// while the current level elements are
// processed we push their children into the
// queue
if (temp.left != null)
q.add(temp.left);
if (temp.right != null)
q.add(temp.right);
}
}
// We reach here if given key x doesn't exist in
// tree
return null;
}
// A utility function to test above functions
void test(Node node, int k)
{
Node nr = nextRight(root, k);
if (nr != null)
System.out.println("Next Right of " + k + " is "
+ nr.data);
else
System.out.println(
"No next right node found for " + k);
}
// Driver program to test above functions
public static void main(String args[])
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(2);
tree.root.right = new Node(6);
tree.root.right.right = new Node(5);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(4);
tree.test(tree.root, 10);
tree.test(tree.root, 2);
tree.test(tree.root, 6);
tree.test(tree.root, 5);
tree.test(tree.root, 8);
tree.test(tree.root, 4);
}
}
// This code is contributed by garg28harsh.
Python
# Python program to find next right of a given key
class Node:
def __init__(self, item):
self.data = item
self.left = None
self.right = None
root = None
# Method to find next right of given key k, it returns
# None if k is not present in tree or k is the
# rightmost node of its level
def nextRight(first, k):
# Base Case
if first is None:
return None
# Create an empty queue for level order traversal
# A queue to store node addresses
res = None
q = []
# Enqueue Root and its level
q.append(first)
# A standard BFS loop
while len(q) != 0:
# Get the count of the elements in the queue,
# this
# is also the count of elements present at the
# current level
n = len(q)
# loop through the elements of the current
# level
for i in range(n):
temp = q[0]
q.pop(0)
# if the key is found we check if there is
# any
# element next to it and return the answer
# accordingally
if temp.data == k:
if i != n - 1:
return q[0]
else:
return None
# while the current level elements are
# processed we push their children into the
# queue
if temp.left is not None:
q.append(temp.left)
if temp.right is not None:
q.append(temp.right)
# We reach here if given key
# x doesn't exist in tree
return None
# A utility function to test above functions
def test(node, k):
nr = nextRight(root, k)
if nr is not None:
print("Next Right of " + str(k) +
" is " + str(nr.data))
else:
print("No next right node found for " +
str(k))
root = Node(10)
root.left = Node(2)
root.right = Node(6)
root.right.right = Node(5)
root.left.left = Node(8)
root.left.right = Node(4)
test(root, 10)
test(root, 2)
test(root, 6)
test(root, 5)
test(root, 8)
test(root, 4)
# contributed by akashish__
C#
// C# program to find next right of a given key
using System;
using System.Collections;
// A binary tree node
public class Node {
public int data;
public Node left, right;
public Node(int item)
{
data = item;
left = right = null;
}
}
// This Code is contributed by karandeep1234
public class BinaryTree {
public Node root;
// Method to find next right of given key k, it returns
// NULL if k is not present in tree or k is the
// rightmost node of its level
public Node nextRight(Node first, int k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for level order traversal
// A queue to store node addresses
// Node res = null;
Queue q = new Queue();
// Enqueue Root and its level
q.Enqueue(first);
// A standard BFS loop
while (q.Count != 0) {
// Get the count of the elements in the queue,
// this
// is also the count of elements present at the
// current level
int n = q.Count;
// loop through the elements of the current
// level
for (int i = 0; i < n; i++) {
Node temp = (Node)q.Peek();
q.Dequeue();
// if the key is found we check if there is
// any
// element next to it and return the answer
// accordingally
if (temp.data == k) {
if (i != n - 1) {
return (Node)q.Peek();
}
else
return null;
}
// while the current level elements are
// processed we push their children into the
// queue
if (temp.left != null)
q.Enqueue(temp.left);
if (temp.right != null)
q.Enqueue(temp.right);
}
}
// We reach here if given key x doesn't exist in
// tree
return null;
}
// A utility function to test above functions
void test(Node node, int k)
{
Node nr = nextRight(root, k);
if (nr != null)
Console.WriteLine("Next Right of " + k + " is "
+ nr.data);
else
Console.WriteLine(
"No next right node found for " + k);
}
// Driver program to test above functions
public static void Main(string[] args)
{
BinaryTree tree = new BinaryTree();
tree.root = new Node(10);
tree.root.left = new Node(2);
tree.root.right = new Node(6);
tree.root.right.right = new Node(5);
tree.root.left.left = new Node(8);
tree.root.left.right = new Node(4);
tree.test(tree.root, 10);
tree.test(tree.root, 2);
tree.test(tree.root, 6);
tree.test(tree.root, 5);
tree.test(tree.root, 8);
tree.test(tree.root, 4);
}
}
JavaScript
// JavaScript program to find next right of a given key
class Node{
constructor(item){
this.data = item;
this.left = this.right = null;
}
}
var root;
// Method to find next right of given key k, it returns
// NULL if k is not present in tree or k is the
// rightmost node of its level
function nextRight(first, k)
{
// Base Case
if (first == null)
return null;
// Create an empty queue for level order traversal
// A queue to store node addresses
var res = null;
var q = [];
// Enqueue Root and its level
q.push(first);
// A standard BFS loop
while (q.length != 0)
{
// Get the count of the elements in the queue,
// this
// is also the count of elements present at the
// current level
var n = q.length;
// loop through the elements of the current
// level
for(let i=0;i<n;i++){
let temp = q[0];
q.shift();
// if the key is found we check if there is
// any
// element next to it and return the answer
// accordingally
if (temp.data == k)
{
if (i != n -1 ){
return q[0];
}
else{
return null;
}
}
// while the current level elements are
// processed we push their children into the
// queue
if (temp.left != null)
{
q.push(temp.left);
}
if (temp.right != null)
{
q.push(temp.right);
}
}
}
// We reach here if given key
// x doesn't exist in tree
return null;
}
// A utility function to test above functions
function test(node, k)
{
let nr = nextRight(root, k);
if (nr != null)
console.log("Next Right of " + k +
" is " + nr.data + "<br>");
else
console.log("No next right node found for " +
k + "<br>");
}
root = new Node(10);
root.left = new Node(2);
root.right = new Node(6);
root.right.right = new Node(5);
root.left.left = new Node(8);
root.left.right = new Node(4);
test(root, 10);
test(root, 2);
test(root, 6);
test(root, 5);
test(root, 8);
test(root, 4);
// This code is contributed by lokeshmvs21.
OutputNo next right node found for 10
Next Right of 2 is 6
No next right node found for 6
No next right node found for 5
Next Right of 8 is 4
Next Right of 4 is 5
Time Complexity: O(N), Although we are using nested loops but if you observe we are just traversing every element of the tree just once.
Auxiliary Space: O(B), Here B is the breadth of the tree and the extra space is used by the elements stored in the queue.
The extra space used in this approach is less than the previous approach as we are using only a single queue.
Exercise: Write a function to find left node of a given node. If there is no node on the left side, then return NULL.
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++ STLIn 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 JavaThe 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
11 min read
Queue in PythonLike 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 ExamplesA 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 JavascriptA 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 LanguageA 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 ScalaA 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
Easy problems on Queue
Detect cycle in an undirected graph using BFSGiven 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 GraphGiven 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 BFSGiven 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 TreeGiven 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 TreeGiven 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 TreeGiven 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 notGiven 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 traversalGiven 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 nodesGiven 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 graphGiven 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 TreeGiven 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 keyGiven 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 1Given 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 BFSGiven 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 streamGiven 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