InterviewPrepKit

Home / Coding / Algorithm & Data Structure / Trees

Populating Next Right Pointers in Each Node II

medium Original ↗ 00:00

Problem

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

Follow-up: solve it using O(1) extra space. The recursion stack does not count as free, so 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 tree shape is allowed; gaps between subtrees are the main 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.

Write your solution, then hit Run tests to check it — or get a mock grade from the AI coach.

The coach remembers this session — revise your code and ask again, and it grades your progress. It gives hints, not the answer.
Report a bug