Skip to content
Decoder

Populating Next Right Pointers in Each Node II

Medium

Problem

Each node of a binary tree has the usual val, left and right, plus a `next` pointer that starts as `None` (null). Given the root, set every node's next to the node immediately to its right on the same level, or leave it None if it is the last node on its level. The tree is not necessarily full: any child may be missing. Return the root.

Use only O(1) extra memory beyond the tree itself (no queue of nodes).

Trees in the examples are written in level order (top to bottom, left to right), with null for a missing child, the same way the tests build them. # marks the end of a level when you follow next pointers.

Example 1

Input
[10, 6, 14, 3, null, 12, 20]
Output
10 # 6 → 14 # 3 → 12 → 20 #

Example 2

Input
[1, 2, 3, 4, null, null, 5]
Output
1 # 2 → 3 # 4 → 5 #

Example 3

Input
[]
Output
(empty)

Constraints

  • 0 <= number of nodes <= 6000
  • -100 <= Node.val <= 100

Read it once before you touch anything

Want some pressure? Start the timer. In an interview you get about two minutes to understand the problem.

  1. 1Read the goalWhat goes in, what comes out
  2. 2Scan the examplesCheck one by hand
  3. 3Note the constraintsThey set your Big O
Say what it asks in one sentence
Say it out loud first, then compare with ours.