Find Nearest Right Node in Binary Tree — LeetCode 1602 Python Solution

MediumLeetCode PremiumTreeBreadth-First SearchBinary Tree
Problem
#1602
Reading time
3 min

The 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.

Example

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.

Python solution

Python
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def findNearestRightNode(self, root: TreeNode, u: TreeNode) -> Optional[TreeNode]:
        q = deque([root])
        while q:
            for i in range(len(q) - 1, -1, -1):
                root = q.popleft()
                if root == u:
                    return q[0] if i else None
                if root.left:
                    q.append(root.left)
                if root.right:
                    q.append(root.right)

Complexity

MeasureComplexity
TimeO(n)
SpaceO(n) auxiliary

Pattern: Tree Traversal

Choose the order — preorder, inorder, postorder, level — and the problem solves itself. LeetCode 1602. Find Nearest Right Node in Binary Tree is filed here because LeetCode tags it Tree and Binary Tree, which is the vocabulary this hub collects.

The tree traversal guide has the Python template for the pattern and the 225 LeetCode problems that use it.

Related problems

Frequently asked questions

How hard is LeetCode 1602. Find Nearest Right Node in Binary Tree?
LeetCode 1602. Find Nearest Right Node in Binary Tree is rated Medium on LeetCode.
What is the time complexity of LeetCode 1602. Find Nearest Right Node in Binary Tree?
The Python solution on this page runs in O(n).
What is the space complexity of LeetCode 1602. Find Nearest Right Node in Binary Tree?
The Python solution on this page uses O(n) auxiliary space.
What topics does LeetCode 1602. Find Nearest Right Node in Binary Tree cover?
LeetCode 1602. Find Nearest Right Node in Binary Tree is tagged Tree, Breadth-First Search and Binary Tree on LeetCode.
Is LeetCode 1602. Find Nearest Right Node in Binary Tree a premium problem?
Yes. LeetCode 1602. Find Nearest Right Node in Binary Tree is a LeetCode Premium problem, so the full statement and test cases require a paid LeetCode subscription.

Stuck on problems like this in a live interview?

Stealth Interview is a desktop app for macOS and Windows. It reads the problem off your screen and returns a working solution with a step-by-step explanation and its time and space complexity — invisible to screen sharing.

Get Stealth Interview