# Find next right node of a given key | Set 2

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
Input : 2
Output : 6

Input : 4
Output : 5
```

## Recommended: Please try your approach on {IDE} first, before moving on to the solution.

In our previous post we have discussed about a solution using Level Order Traversal. In this post we will discuss about a solution based on Preorder traversal which takes constant auxiliary space.

The idea is to traverse the given tree using preorder traversal and search for the given key. Once we found the given key, we will mark the level number for this key. Now the next node we will find at the same level is the required node which is at the right of given key.

Below is the implementation of above idea:

## C++

 `/* C++ program to find next right of a given key  ` `   ``using preorder traversal */` `#include ` `using` `namespace` `std; ` ` `  `// A Binary Tree Node ` `struct` `Node { ` `    ``struct` `Node *left, *right; ` `    ``int` `key; ` `}; ` ` `  `// 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; ` `} ` ` `  `// Function to find next node for given node ` `// in same level in a binary tree by using ` `// pre-order traversal ` `Node* nextRightNode(Node* root, ``int` `k, ``int` `level,  ` `                               ``int``& value_level) ` `{ ` `    ``// return null if tree is empty ` `    ``if` `(root == NULL) ` `        ``return` `NULL; ` ` `  `    ``// if desired node is found, set value_level ` `    ``// to current level ` `    ``if` `(root->key == k) { ` `        ``value_level = level; ` `        ``return` `NULL; ` `    ``} ` ` `  `    ``// if value_level is already set, then current ` `    ``// node is the next right node ` `    ``else` `if` `(value_level) { ` `        ``if` `(level == value_level) ` `            ``return` `root; ` `    ``} ` ` `  `    ``// recurse for left subtree by increasing level by 1 ` `    ``Node* leftNode = nextRightNode(root->left, k,  ` `                        ``level + 1,  value_level); ` ` `  `    ``// if node is found in left subtree, return it ` `    ``if` `(leftNode) ` `        ``return` `leftNode; ` ` `  `    ``// recurse for right subtree by increasing level by 1 ` `    ``return` `nextRightNode(root->right, k, level + 1, ` `                                       ``value_level); ` `} ` ` `  `// Function to find next node of given node in the ` `//  same level in given binary tree ` `Node* nextRightNodeUtil(Node* root, ``int` `k) ` `{ ` `    ``int` `value_level = 0; ` ` `  `    ``return` `nextRightNode(root, k, 1, value_level); ` `} ` ` `  `// A utility function to test above functions ` `void` `test(Node* root, ``int` `k) ` `{ ` `    ``Node* nr = nextRightNodeUtil(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  ` `using preorder traversal */` `import` `java.util.*; ` `class` `GfG { ` `     `  `static` `class` `V { ` `    ``int` `value_level = ``0``; ` `} ` ` `  `// A Binary Tree Node  ` `static` `class` `Node {  ` `    ``Node left, right;  ` `    ``int` `key;  ` `} ` ` `  `// Utility function to create a new tree node  ` `static` `Node newNode(``int` `key)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.key = key;  ` `    ``temp.left = ``null``; ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Function to find next node for given node  ` `// in same level in a binary tree by using  ` `// pre-order traversal  ` `static` `Node nextRightNode(Node root, ``int` `k, ``int` `level, V value)  ` `{  ` `    ``// return null if tree is empty  ` `    ``if` `(root == ``null``)  ` `        ``return` `null``;  ` ` `  `    ``// if desired node is found, set value_level  ` `    ``// to current level  ` `    ``if` `(root.key == k) {  ` `        ``value.value_level = level;  ` `        ``return` `null``;  ` `    ``}  ` ` `  `    ``// if value_level is already set, then current  ` `    ``// node is the next right node  ` `    ``else` `if` `(value.value_level != ``0``) {  ` `        ``if` `(level == value.value_level)  ` `            ``return` `root;  ` `    ``}  ` ` `  `    ``// recurse for left subtree by increasing level by 1  ` `    ``Node leftNode = nextRightNode(root.left, k, level + ``1``, value);  ` ` `  `    ``// if node is found in left subtree, return it  ` `    ``if` `(leftNode != ``null``)  ` `        ``return` `leftNode;  ` ` `  `    ``// recurse for right subtree by increasing level by 1  ` `    ``return` `nextRightNode(root.right, k, level + ``1``, value);  ` `}  ` ` `  `// Function to find next node of given node in the  ` `// same level in given binary tree  ` `static` `Node nextRightNodeUtil(Node root, ``int` `k)  ` `{  ` `    ``V v = ``new` `V(); ` ` `  `    ``return` `nextRightNode(root, k, ``1``, v);  ` `}  ` ` `  `// A utility function to test above functions  ` `static` `void` `test(Node root, ``int` `k)  ` `{  ` `    ``Node nr = nextRightNodeUtil(root, k);  ` `    ``if` `(nr != ``null``)  ` `        ``System.out.println(``"Next Right of "` `+ k + ``" is "``+ nr.key);  ` `    ``else` `        ``System.out.println(``"No next right node found for "` `+ k); ` `}  ` ` `  `// Driver program to test above functions  ` `public` `static` `void` `main(String[] args)  ` `{  ` `    ``// 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``);  ` `}  ` `}  `

## Python3

 `# Python3 program to find next right of a  ` `# given key using preorder traversal  ` ` `  `# class to create a new tree node  ` `class` `newNode: ` `    ``def` `__init__(``self``, key): ` `        ``self``.key ``=` `key  ` `        ``self``.left ``=` `self``.right ``=` `None` ` `  `# Function to find next node for given node  ` `# in same level in a binary tree by using  ` `# pre-order traversal  ` `def` `nextRightNode(root, k, level, value_level): ` `     `  `    ``# return None if tree is empty  ` `    ``if` `(root ``=``=` `None``): ` `        ``return` `None` ` `  `    ``# if desired node is found, set  ` `    ``# value_level to current level  ` `    ``if` `(root.key ``=``=` `k):  ` `        ``value_level[``0``] ``=` `level  ` `        ``return` `None` ` `  `    ``# if value_level is already set, then ` `    ``# current node is the next right node  ` `    ``elif` `(value_level[``0``]):  ` `        ``if` `(level ``=``=` `value_level[``0``]):  ` `            ``return` `root ` ` `  `    ``# recurse for left subtree by increasing ` `    ``# level by 1  ` `    ``leftNode ``=` `nextRightNode(root.left, k,  ` `                             ``level ``+` `1``, value_level)  ` ` `  `    ``# if node is found in left subtree,  ` `    ``# return it  ` `    ``if` `(leftNode): ` `        ``return` `leftNode  ` ` `  `    ``# recurse for right subtree by  ` `    ``# increasing level by 1  ` `    ``return` `nextRightNode(root.right, k,  ` `                         ``level ``+` `1``, value_level) ` ` `  `# Function to find next node of given node  ` `# in the same level in given binary tree  ` `def` `nextRightNodeUtil(root, k): ` `    ``value_level ``=` `[``0``] ` ` `  `    ``return` `nextRightNode(root, k, ``1``, value_level)  ` ` `  `# A utility function to test above functions  ` `def` `test(root, k): ` `    ``nr ``=` `nextRightNodeUtil(root, k)  ` `    ``if` `(nr !``=` `None``):  ` `        ``print``(``"Next Right of"``, k, ``"is"``, nr.key)  ` `    ``else``: ` `        ``print``(``"No next right node found for"``, k) ` ` `  `# Driver Code ` `if` `__name__ ``=``=` `'__main__'``: ` `     `  `    ``# Let us create binary tree given in the  ` `    ``# above example  ` `    ``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``) ` ` `  `# This code is contributed by PranchalK `

## C#

 `/* C# program to find next right of a given key  ` `using preorder traversal */` `using` `System; ` ` `  `class` `GfG  ` `{  ` `     `  `public` `class` `V  ` `{  ` `    ``public` `int` `value_level = 0;  ` `}  ` ` `  `// A Binary Tree Node  ` `public` `class` `Node ` `{  ` `    ``public` `Node left, right;  ` `    ``public` `int` `key;  ` `}  ` ` `  `// Utility function to create a new tree node  ` `static` `Node newNode(``int` `key)  ` `{  ` `    ``Node temp = ``new` `Node();  ` `    ``temp.key = key;  ` `    ``temp.left = ``null``;  ` `    ``temp.right = ``null``;  ` `    ``return` `temp;  ` `}  ` ` `  `// Function to find next node for given node  ` `// in same level in a binary tree by using  ` `// pre-order traversal  ` `static` `Node nextRightNode(Node root, ``int` `k, ` `                            ``int` `level, V value)  ` `{  ` `    ``// return null if tree is empty  ` `    ``if` `(root == ``null``)  ` `        ``return` `null``;  ` ` `  `    ``// if desired node is found, set  ` `    ``// value_level to current level  ` `    ``if` `(root.key == k) ` `    ``{  ` `        ``value.value_level = level;  ` `        ``return` `null``;  ` `    ``}  ` ` `  `    ``// if value_level is already set, then current  ` `    ``// node is the next right node  ` `    ``else` `if` `(value.value_level != 0)  ` `    ``{  ` `        ``if` `(level == value.value_level)  ` `            ``return` `root;  ` `    ``}  ` ` `  `    ``// recurse for left subtree by increasing level by 1  ` `    ``Node leftNode = nextRightNode(root.left, ` `                            ``k, level + 1, value);  ` ` `  `    ``// if node is found in left subtree, return it  ` `    ``if` `(leftNode != ``null``)  ` `        ``return` `leftNode;  ` ` `  `    ``// recurse for right subtree by ` `    ``// increasing level by 1  ` `    ``return` `nextRightNode(root.right, k, ` `                       ``level + 1, value);  ` `}  ` ` `  `// Function to find next node of given node in the  ` `// same level in given binary tree  ` `static` `Node nextRightNodeUtil(Node root, ``int` `k)  ` `{  ` `    ``V v = ``new` `V();  ` ` `  `    ``return` `nextRightNode(root, k, 1, v);  ` `}  ` ` `  `// A utility function to test above functions  ` `static` `void` `test(Node root, ``int` `k)  ` `{  ` `    ``Node nr = nextRightNodeUtil(root, k);  ` `    ``if` `(nr != ``null``)  ` `        ``Console.WriteLine(``"Next Right of "` `+ ` `                            ``k + ``" is "``+ nr.key);  ` `    ``else` `        ``Console.WriteLine(``"No next right node"` `+ ` `                            ``" found for "` `+ k);  ` `}  ` ` `  `// Driver main ` `public` `static` `void` `Main(String[] args)  ` `{  ` `    ``// 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);  ` `}  ` `}  ` ` `  `// This code contributed by Rajput-Ji `

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)
Auxiliary Space: O(1)

Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.

My Personal Notes arrow_drop_up Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :
Practice Tags :

1

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.