Find next right node of a given key
Last Updated :
19 Jan, 2023
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.
For example, consider the following Binary Tree. Output for 2 is 6, output for 4 is 5. Output for 10, 6 and 5 is NULL.
10
/ \
2 6
/ \ \
8 4 5
Solution: 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++
#include <iostream>
#include <queue>
using namespace std;
struct node
{
struct node *left, *right;
int key;
};
node* nextRight(node *root, int k)
{
if (root == NULL)
return 0;
queue<node *> qn;
queue< int > ql;
int level = 0;
qn.push(root);
ql.push(level);
while (qn.size())
{
node *node = qn.front();
level = ql.front();
qn.pop();
ql.pop();
if (node->key == k)
{
if (ql.size() == 0 || ql.front() != level)
return NULL;
return qn.front();
}
if (node->left != NULL)
{
qn.push(node->left);
ql.push(level+1);
}
if (node->right != NULL)
{
qn.push(node->right);
ql.push(level+1);
}
}
return NULL;
}
node* newNode( int key)
{
node *temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
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;
}
int main()
{
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
import java.util.LinkedList;
import java.util.Queue;
class Node
{
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree
{
Node root;
Node nextRight(Node first, int k)
{
if (first == null )
return null ;
Queue<Node> qn = new LinkedList<Node>();
Queue<Integer> ql = new LinkedList<Integer>();
int level = 0 ;
qn.add(first);
ql.add(level);
while (qn.size() != 0 )
{
Node node = qn.peek();
level = ql.peek();
qn.remove();
ql.remove();
if (node.data == k)
{
if (ql.size() == 0 || ql.peek() != level)
return null ;
return qn.peek();
}
if (node.left != null )
{
qn.add(node.left);
ql.add(level + 1 );
}
if (node.right != null )
{
qn.add(node.right);
ql.add(level + 1 );
}
}
return null ;
}
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);
}
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 );
}
}
|
Python3
class Node:
def __init__( self , key):
self .key = key
self .left = None
self .right = None
def nextRight(root, k):
if root is None :
return 0
qn = []
q1 = []
level = 0
qn.append(root)
q1.append(level)
while ( len (qn) > 0 ):
node = qn.pop( 0 )
level = q1.pop( 0 )
if node.key = = k :
if ( len (q1) = = 0 or q1[ 0 ] ! = level):
return None
return qn[ 0 ]
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 )
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))
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 )
|
C#
using System;
using System.Collections.Generic;
public class Node
{
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree
{
Node root;
Node nextRight(Node first, int k)
{
if (first == null )
return null ;
Queue<Node> qn = new Queue<Node>();
Queue< int > ql = new Queue< int >();
int level = 0;
qn.Enqueue(first);
ql.Enqueue(level);
while (qn.Count != 0)
{
Node node = qn.Peek();
level = ql.Peek();
qn.Dequeue();
ql.Dequeue();
if (node.data == k)
{
if (ql.Count == 0 || ql.Peek() != level)
return null ;
return qn.Peek();
}
if (node.left != null )
{
qn.Enqueue(node.left);
ql.Enqueue(level + 1);
}
if (node.right != null )
{
qn.Enqueue(node.right);
ql.Enqueue(level + 1);
}
}
return null ;
}
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);
}
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
<script>
class Node
{
constructor(item)
{
this .data = item;
this .left = this .right = null ;
}
}
let root;
function nextRight(first, k)
{
if (first == null )
return null ;
let qn = [];
let ql = [];
let level = 0;
qn.push(first);
ql.push(level);
while (qn.length != 0)
{
let node = qn[0];
level = ql[0];
qn.shift();
ql.shift();
if (node.data == k)
{
if (ql.length == 0 || ql[0] != level)
return null ;
return qn[0];
}
if (node.left != null )
{
qn.push(node.left);
ql.push(level + 1);
}
if (node.right != null )
{
qn.push(node.right);
ql.push(level + 1);
}
}
return null ;
}
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>" );
}
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);
</script>
|
Output
No 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++
#include <iostream>
#include <queue>
using namespace std;
struct node {
struct node *left, *right;
int key;
};
node* nextRight(node* root, int key)
{
if (root == NULL)
return NULL;
node* res = NULL;
queue<node*> q;
q.push(root);
while (!q.empty()) {
int n = q.size();
for ( int i = 0; i < n; i++) {
node* temp = q.front();
q.pop();
if (temp->key == key) {
if (i != n - 1)
return q.front();
else
return NULL;
}
if (temp->left)
q.push(temp->left);
if (temp->right)
q.push(temp->right);
}
}
return NULL;
}
node* newNode( int key)
{
node* temp = new node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
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;
}
int main()
{
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
import java.util.LinkedList;
import java.util.Queue;
class Node {
int data;
Node left, right;
Node( int item)
{
data = item;
left = right = null ;
}
}
class BinaryTree {
Node root;
Node nextRight(Node first, int k)
{
if (first == null )
return null ;
Node res = null ;
Queue<Node> q = new LinkedList<Node>();
q.add(first);
while (q.size() != 0 ) {
int n = q.size();
for ( int i = 0 ; i < n; i++) {
Node temp = q.peek();
q.remove();
if (temp.data == k) {
if (i != n - 1 ) {
return q.peek();
}
else
return null ;
}
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
}
}
return null ;
}
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);
}
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 );
}
}
|
C#
using System;
using System.Collections;
public class Node {
public int data;
public Node left, right;
public Node( int item)
{
data = item;
left = right = null ;
}
}
public class BinaryTree {
public Node root;
public Node nextRight(Node first, int k)
{
if (first == null )
return null ;
Queue q = new Queue();
q.Enqueue(first);
while (q.Count != 0) {
int n = q.Count;
for ( int i = 0; i < n; i++) {
Node temp = (Node)q.Peek();
q.Dequeue();
if (temp.data == k) {
if (i != n - 1) {
return (Node)q.Peek();
}
else
return null ;
}
if (temp.left != null )
q.Enqueue(temp.left);
if (temp.right != null )
q.Enqueue(temp.right);
}
}
return null ;
}
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);
}
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
class Node{
constructor(item){
this .data = item;
this .left = this .right = null ;
}
}
var root;
function nextRight(first, k)
{
if (first == null )
return null ;
var res = null ;
var q = [];
q.push(first);
while (q.length != 0)
{
var n = q.length;
for (let i=0;i<n;i++){
let temp = q[0];
q.shift();
if (temp.data == k)
{
if (i != n -1 ){
return q[0];
}
else {
return null ;
}
}
if (temp.left != null )
{
q.push(temp.left);
}
if (temp.right != null )
{
q.push(temp.right);
}
}
}
return null ;
}
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);
|
Python3
class Node:
def __init__( self , item):
self .data = item
self .left = None
self .right = None
root = None
def nextRight(first, k):
if first is None :
return None
res = None
q = []
q.append(first)
while len (q) ! = 0 :
n = len (q)
for i in range (n):
temp = q[ 0 ]
q.pop( 0 )
if temp.data = = k:
if i ! = n - 1 :
return q[ 0 ]
else :
return None
if temp.left is not None :
q.append(temp.left)
if temp.right is not None :
q.append(temp.right)
return None
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 )
|
Output
No 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.
This approach was contributed by Abhijeet Kumar.
Exercise: Write a function to find left node of a given node. If there is no node on the left side, then return NULL.
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...