Leetcode Problem 1602. Find Nearest Right Node in Binary Tree

1602. Find Nearest Right Node in Binary Tree

Leetcode Solutions

BFS: One Queue + Level Size Measurements

  1. Initialize a queue and add the root node to it.
  2. While the queue is not empty: a. Record the number of nodes in the current level (level size). b. Iterate over the nodes in the current level: i. Dequeue a node from the queue. ii. If this node is u, check if there is another node in the queue (which would be the right neighbor). If so, return it; otherwise, return null. iii. Enqueue the left and right children of the current node if they exist.
  3. If the end of the queue is reached without finding u, return null.
UML Thumbnail

BFS: Two Queues

Ask Question

Programming Language
image/screenshot of info(optional)
Full Screen
Loading...

Suggested Answer

Answer
Full Screen
Copy Answer Code
Loading...