#1602
Medium Algorithms Find nearest right node in binary tree
Tree Breadth-First Search Binary Tree
75.1% acceptance
Mar 31, 2026
333
10
Given the root of a binary tree and a node u in the tree, return the nearest node on the same level that is to the right of u, or return null if u is the rightmost node in its level.
Solution
C++
Time O(n²)
Space O(1)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode() : val(0), left(nullptr), right(nullptr) {}
* TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
* TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
* };
*/
class Solution {
public:
TreeNode* findNearestRightNode(TreeNode* root, TreeNode* u) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int sz = q.size();
for (int i = 0; i < sz; i++) {
TreeNode* node = q.front(); q.pop();
if (node == u) {
return (i < sz - 1) ? q.front() : nullptr;
}
if (node->left) q.push(node->left);
if (node->right) q.push(node->right);
}
}
return nullptr;
}
};