595. Find Nearest Right Node in Binary Tree

Given the root of a binary tree and a target node, return the nearest node on the same level that is to the right of the target node. If there is no such node, return null.

Example 1:

Input: root = [1,2,3,null,4,5,6], target = 4

Output: 5

Explanation: The nearest right node of 4 is 5.

Example 2:

Input: root = [1,2,3,null,4,5,6], target = 6

Output: null

Explanation: The nearest right node of 6 is null since it is the last node in its level.

Now Your Turn!

Pick the correct output for the given input

Input: root = [3,null,4,2] , target = 2

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • The number of nodes in the tree is in the range [1,105].
  • 1 <= Node.val <= 105
  • All values in the tree are distinct.
  • target is a node in the binary tree rooted at root.

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

0
/**
* Definition for a binary tree node.
* class TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : data(0), left(nullptr), right(nullptr) {}
* };
*/
class Solution {
public:
TreeNode* findNearestRightNode(TreeNode* root, TreeNode* target) {
}
};
 
Test Case

Input:

Root
Target