Find Nearest Right Node in Binary Tree - Problem
Find Nearest Right Node in Binary Tree
You're given the
What does "nearest right node" mean?
- It must be on the same level (depth) as node
- It must be to the right of
- It should be the immediate next node to the right, not just any node to the right
If
Example:
Level 2 has nodes: [4,5,6,7]
Node 4's nearest right neighbor is node 5.
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 = 4Level 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
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!
๐ก
Explanation
AI Ready
๐ก Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code