1625. Next Door on the Floor

Easy1.5 points estimatedBinary TreeBreadth-First Search

Guests in a hall are arranged as a binary tree, and you read the tree level by level. Two nodes are on the same level when they have the same distance from the root, even if their parents differ.

Given the root of the tree and an integer target, find the node whose value equals target and return the node that stands immediately to its right on the same level, that is, the next node in the left-to-right order of that level. Return the actual node object of the input tree, or null if the target node is the rightmost node of its level (including the root).

All node values are distinct and target is guaranteed to be present. Use a breadth-first traversal that processes one level at a time. Target complexity: O(n) time, O(w) space where w is the widest level.

Example 1

Input:
root = [3,9,20,null,null,15,7], target = 9
Output:
2
Explanation:

Nodes 9 and 20 share depth 2, so the neighbour of 9 is the node valued 20.

Example 2

Input:
root = [3,9,20,null,null,15,7], target = 7
Output:
null
Explanation:

Node 7 is the last node on its level, so there is no neighbour.

Example 3

Input:
root = [1,2,3,4,null,null,5], target = 4
Output:
4
Explanation:

On level 3, node 4 is followed by node 5 even though they have different parents.

Constraints

1 ≤ nodes ≤ 1000

All node values are distinct, and target occurs in the tree

How this problem is judged

Answers
Your answer must match exactly. Numbers compare by value, so 2 and 2.0 are equal.
Time per case
Python 1,200 msC++ 300 msJava 600 msJavaScript 600 msTypeScript 600 ms

Expected complexity

Time
O(n)
Space
O(n)

What the author was aiming for. Your own solution is not measured against it.

Asked in an interview

Were you asked this in an interview? Say where, anonymously.

Code
Loading the editor…