Medium · Trees

Populate next pointers to right

Given the root of a perfect binary tree (every internal node has two children and all leaves are on the same level), set each node's next pointer to the node immediately to its right on the same level, or to null for the last node of each level, and return the root.

Examples

Example 1

{
  "tree": [1, 2, 3, 4, 5, 6, 7]
}

Output: 4 next-links set

Example 2

{
  "tree": [1, 2, 3]
}

Output: 1 next-link set

Rebuild it in the studio

Read every interview problem free. Ten rooms need no account. A token opens a problem in full — Pro never counts.

More Trees problems