899. Populating Next Right Pointers in Each Node

MediumTreesBinary TreeBFS

Given the root of a binary tree, populate each node's next pointer to point to its immediate right neighbor on the same level; the rightmost node of each level points to nothing. Return, in level order, the value of each node's next pointer (or -1 if none). The tree is given as a level-order array.

Input: A level-order array of the tree.

Output: Array — each node's next value (or -1), in level order.

Examples

Example 1
Input: [1,2,3,4,5,6,7]
Output: [-1,3,-1,5,6,7,-1]
Explanation: Each node links to its right neighbor.
Example 2
Input: [1]
Output: [-1]
Explanation: Root has no neighbor.
Example 3
Input: []
Output: []
Explanation: Empty tree.

Constraints

Asked by

BloombergMetaAmazonMicrosoftOracleGoogle
Solve this problem in the editor →