Talentd
FleetCode

1602. Find Nearest Right Node in Binary Tree

Medium75.2% acceptance1 companyPremium elsewhere, free here

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.

Example 1:

Input: root = [1,2,3,null,4,5,6], u = 4
Output: 5
Explanation: The nearest node on the same level to the right of node 4 is node 5.

Example 2:

Input: root = [3,null,4,2], u = 2
Output: null
Explanation: There are no nodes to the right of 2.

Constraints:

  • The number of nodes in the tree is in the range [1, 105].
  • 1 <= Node.val <= 105
  • All values in the tree are distinct.
  • u is a node in the binary tree rooted at root.

Asked at 1 company

Hints open one at a time

Hint 1
Use BFS, traverse the tree level by level and always push the left node first
Hint 2
When you reach the target node, mark a boolean variable true
Hint 3
If you meet another node in the same level after marking the boolean true, return this node.
Hint 4
If you did not meet new nodes in the same level and started traversing a new level, return Null
5:33
Still stuck?Read 2 approaches, or watch a walkthrough.
Open solution
Loading editor…
1class Solution:
2 def solve(self):
3 pass
4
Starter codePython 3Spaces: 4
Examples
Input
[1,2,3,null,4,5,6]
4
Input
[3,null,4,2]
2
Your code is saved on this device.Solution