Find Nearest Right Node in Binary Tree - Problem
Find Nearest Right Node in Binary Tree

You're given the root of a binary tree and a specific node u that exists somewhere in the tree. Your task is to find the nearest node to the right of u on the same level.

What does "nearest right node" mean?
- It must be on the same level (depth) as node u
- It must be to the right of u when you traverse the level from left to right
- It should be the immediate next node to the right, not just any node to the right

If u is already the rightmost node on its level, return null.

Example:
Tree: [1,2,3,4,5,6,7], u = 4
Level 2 has nodes: [4,5,6,7]
Node 4's nearest right neighbor is node 5.

Input & Output

example_1.py โ€” Basic Case
$ Input: root = [1,2,3,4,5,6,7], u = 4
โ€บ Output: 5
๐Ÿ’ก Note: Node 4 is at level 2. The nodes at level 2 are [4,5,6,7]. The immediate right neighbor of node 4 is node 5.
example_2.py โ€” Rightmost Node
$ Input: root = [1,2,3,null,4,5,6], u = 6
โ€บ Output: null
๐Ÿ’ก Note: Node 6 is at level 2 and is the rightmost node at that level. Since there's no node to its right, we return null.
example_3.py โ€” Single Node Level
$ Input: root = [1,2,null,3], u = 1
โ€บ Output: null
๐Ÿ’ก Note: Node 1 is at level 0 and is the only node at that level. There's no right neighbor, so return null.

Constraints

  • The number of nodes in the tree is in the range [1, 104]
  • 1 โ‰ค Node.val โ‰ค 105
  • All node values are unique
  • u is guaranteed to be a node in the tree

Visualization

Tap to expand
๐ŸŽญ Movie Theater AnalogyMovie ScreenRow 01Row 123Row 24You5Next67โ†’๐ŸŽฏ Solution Process1. Usher starts from top row (BFS level-order)2. Goes left-to-right in each row3. Finds you (node 4) in Row 24. Next person in same row โ†’ Answer!
Understanding the Visualization
1
Row-by-Row Search
An usher guides visitors row by row, left to right, just like BFS
2
Spot Yourself
When the usher reaches you, you're the target node u
3
Next Person
The very next person the usher encounters in your row is your right neighbor
4
End of Row
If you're the last person in your row, there's no right neighbor
Key Takeaway
๐ŸŽฏ Key Insight: BFS naturally processes nodes left-to-right within each level, making it perfect for finding the immediate right neighbor!
Asked in
Facebook 45 Amazon 38 Microsoft 32 Google 28
35.6K Views
Medium Frequency
~15 min Avg. Time
1.5K 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