InterviewPrepKit

Home / Coding / Trees

Populating Next Right Pointers in Each Node II

medium Original ↗
Solving tips
  • Key insight for O(1) space: once level L's next pointers are wired, level L IS a linked list, so walking it visits level L+1's children left-to-right without a queue.
  • Use a dummy head and a tail pointer for the level being built: walk parents via next, and for each existing child do tail.next = child; tail = child; then level_head = dummy.next. O(n) time, O(1) space.
  • A BFS with a queue is the easy O(n)-time baseline but uses O(w) space and ignores the follow-up.
  • Pitfall: advance across the level with node = node.next (not node.left), don't assume version I's perfect-tree shortcut (missing children break it), and the rightmost node's next stays None.

Problem

You are given a binary tree whose nodes carry an extra pointer field next, initially None everywhere. Wire up every next pointer to point at the node immediately to its right on the same level; the rightmost node of each level keeps next = None. Return the root. Unlike the easier version I of this problem, the tree is not perfect — nodes may be missing anywhere, so a node’s next-right neighbor might live under a distant cousin.

The follow-up that makes this interesting: do it with O(1) extra space (recursion stack not counted as free — the intended answer uses no queue and no recursion proportional to n).

Examples

  • Input: root = [1,2,3,4,5,null,7] → Output: [1,#,2,3,#,4,5,7,#] Level by level (# ends a level): 1; 2 → 3; 4 → 5 → 7. Note 5.next is 7, a cousin under 3, not a sibling.
  • Input: root = [2,1,3] → Output: [2,#,1,3,#] 1.next = 3; both 2 and 3 end their levels with None.
  • Input: root = [] → Output: [] Empty tree — nothing to wire.

Constraints

  • 0 <= n <= 6000 nodes; -100 <= Node.val <= 100.
  • Any shape allowed — gaps between subtrees are the whole difficulty.
  • Target: O(n) time; the follow-up asks for O(1) auxiliary space.

Think about it first

Hint 1 A BFS that processes one level per queue drain sees each level's nodes left to right — linking consecutive dequeued nodes is almost free.
Hint 2 Once level L's `next` pointers are wired, level L is itself a linked list. Can you walk that list to visit level L+1's nodes in left-to-right order without a queue?
Hint 3 Use a dummy head and a `tail` pointer for the level being built: walk the current level via `next`, and for each existing child do `tail.next = child; tail = child`. When the walk ends, `dummy.next` is the start of the next level. That's the O(1)-space answer.
Your workspace Not runnable by design — this is your interview scratchpad. Saved on this device.