AlgoInsight

DSA problem

Populating Next Right Pointers in Each Node II

MediumTree Traversal - Level OrderPattern: Tree Traversal - Level Ordertop300AmazonMicrosoftMetaGoogleBloomberg

Given the root of a binary tree (not necessarily perfect, so some nodes may have zero, one, or two children) where each node has an extra next pointer initially set to null, populate every next pointer so that it points to the node immediately to its right on the same level; otherwise leave it as null. Return the root.

This is the harder cousin of the perfect-tree version. We can no longer assume each parent has both children, so the "use cur.next.left to bridge subtrees" trick fails — cur.next.left might be null even though some node further along the level has children. We need a way to find the next non-null child as we sweep across a level.

The trick is a sentinel (dummy) node for the level being built. As we walk across the parent level (using next pointers already populated there), we attach each child we discover to a growing tail that started at the dummy. After the parent-level sweep finishes, the dummy's next points to the leftmost node of the new level, and the chain of next pointers along the new level is automatically complete.

The outer loop runs once per level until the level being built is empty. Inside, two pointers cur (walks the parent level) and tail (grows the child level) drive the work. Total work is O(n); aside from the dummy node, no auxiliary collection is allocated, giving O(1) extra space — the gold standard for this problem.

Examples

Example 1
Input: root = [1,2,3,4,5,null,7]
Output: [1,#,2,3,#,4,5,7,#]
Explanation: Level 0: 1->#. Level 1: 2->3->#. Level 2: 4->5->7-># (the missing right child of 3 is skipped; the dummy/sentinel pattern handles this transparently).
Example 2
Input: root = []
Output: []
Explanation: An empty tree returns null.
Example 3
Input: root = [1,2,null,3]
Output: [1,#,2,#,3,#]
Explanation: Every level happens to have one node, but the algorithm still wires their next pointers to null correctly.

Constraints

3 hints and a full solution walkthrough with step-by-step visualizations are available in the practice editor.

binary-treebfslevel-orderin-place

Browse all DSA problems