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
Find Nearest Right Node: Input → Process → Output12345Input TreeTarget u = 4 (green)Level-Order BFSLevel 0: [1]Level 1: [2, 3]Level 2: [4, 5]Found u=4 at index 0Next node: 5Process5OutputRight neighbor of 4🎯 Key: BFS processes levels left-to-right, perfect for finding same-level neighbors!
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
Asked in
Facebook 15 Microsoft 12 Amazon 8 Google 6
23.5K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen