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 in Binary Tree INPUT Binary Tree Structure 1 2 3 4 u 5 6 7 root = [1,2,3,4,5,6,7] u = 4 Target node u Answer Other ALGORITHM (BFS) 1 Initialize Queue Start with root node 2 Process Level by Level Track level size for BFS 3 Find Target Node u When found, check right 4 Return Right Neighbor Or null if rightmost Level 2 Queue State: 4 5 6 7 right Time: O(n) | Space: O(w) w = max width of tree RESULT Same Level Nodes: 4 5 Node 5 is immediately to the right of node 4 Output: 5 OK - Found! Right neighbor exists If u=7, return null (rightmost in level) Key Insight: BFS processes nodes level by level from left to right. When we find target node u, the next node in the same level iteration is the nearest right node. If u is the last node processed in that level, it means u is the rightmost node --> return null. TutorialsPoint - Find Nearest Right Node in Binary Tree | BFS Approach
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