AAlgoLoopSpaced repetition for LeetCode
MEDIUMTree / RecursionLeetCode ↗

Populating Next Right Pointers in Each Node II

The key idea

Once a level is fully wired, its next pointers form a singly linked list you can walk left to right. While walking that level, stitch the children of each node onto a new linked list for the next level using a dummy head and a moving tail. This lets you reach every node of the next level without a queue, so the traversal uses only O(1) extra space.

Problem

You are given a binary tree where each node has an extra next pointer. Populate every next pointer so it points to the node immediately to its right on the same level. If there is no node to the right, set next to null.

Unlike the perfect-tree version, this tree is not necessarily complete, so a level can have gaps. Initially every next pointer is set to null.

You may only use constant extra space. The recursion stack of an implicit recursive solution does not count as extra space for this problem.

Constraints

Examples

Input: root = [1,2,3,4,5,null,7] Output: [1,#,2,3,#,4,5,7,#]
Input: root = [] Output: []

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More Tree / Recursion problems