Find Nearest Right Node in Binary Tree Problem
Description
LeetCode Problem 1602.
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.
Example 1:

Input: root = [1,2,3,null,4,5,6], u = 4
Output: 5
Explanation: The nearest node on the same level to the right of node 4 is node 5.
Example 2:

Input: root = [3,null,4,2], u = 2
Output: null
Explanation: There are no nodes to the right of 2.
Constraints:
- The number of nodes in the tree is in the range
[1, 10^5]. 1 <= Node.val <= 10^5- All values in the tree are distinct.
uis a node in the binary tree rooted atroot.
Solution
Approach: Level-Order Traversal (BFS)
A breadth-first search visits the tree level by level, and within each level from left to right. So the node we want is simply the one right after u in its level.
Process one level at a time. Walk through the nodes of the current level while collecting their children for the next level. When the current node is u:
- if there is another node after it on this level, that node is the answer;
- otherwise
uis the rightmost node of its level, and the answer isnull.
Compare nodes by identity (the reference), not by value. Values are distinct here, but the input is a node, so identity is the natural test.
Complexity: O(n) time and O(w) extra space, where w is the largest number of nodes on one level.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]:
level = [root]
while level:
next_level = []
for i, node in enumerate(level):
if node is u:
# The next node on this level, or None if u is the last one.
return level[i + 1] if i + 1 < len(level) else None
if node.left:
next_level.append(node.left)
if node.right:
next_level.append(node.right)
level = next_level
return None