Find Nearest Right Node in Binary Tree - Problem
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.
The tree is guaranteed to contain the given node u.
Input & Output
Example 1 — Basic Right Neighbor
$
Input:
root = [1,2,3,4,5,6,7], u = 4
›
Output:
5
💡 Note:
Node 4 is at level 2 with nodes [4,5,6,7]. The nearest right node is 5.
Example 2 — Rightmost Node
$
Input:
root = [1,2,3,4,5,6,7], u = 7
›
Output:
null
💡 Note:
Node 7 is the rightmost node at level 2, so there's no right neighbor.
Example 3 — Root Level
$
Input:
root = [1,2,3], u = 1
›
Output:
null
💡 Note:
Node 1 is at level 0 by itself, so there's no right neighbor.
Constraints
- The number of nodes in the tree is in the range [1, 104]
- 1 ≤ Node.val ≤ 105
- All values in the tree are unique
- u is guaranteed to be a node in the tree
Visualization
Tap to expand
Understanding the Visualization
1
Input Tree
Binary tree with target node marked
2
Level Processing
Process nodes level by level left to right
3
Right Neighbor
Return next node in same level or null
Key Takeaway
🎯 Key Insight: BFS naturally processes nodes level by level, making it perfect for finding same-level neighbors
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code