Populating Next Right Pointers in Each Node II

MediumTrees · Level Order · Linked Levels🧩 Tree BFS (Level Order)LeetCode #117 ↗Updated

Problem

Each node of an arbitrary (not necessarily perfect) binary tree has an extra next pointer, initially null. Point every node's next to the node immediately to its right on the same level, or leave it null if it is the last one. Return the root.
Input[1,2,3,4,5,null,7]Output[1,#,2,3,#,4,5,7,#]
Input[]Output[]

0 ≤ nodes ≤ 6000  ·  -100 ≤ Node.val ≤ 100  ·  Follow-up: O(1) extra space (recursion stack is not counted).

Try it yourself

Java
class Solution {
    public Node connect(Node root) {
        
    }
}
Your code is saved in this browser.Submit on LeetCode ↗
Key insight
Once a level is wired up, it is a linked list. Walk it with next and, as you go, append its children to a new list for the level below (a dummy head + tail pointer) — no queue needed.
PatternTree BFS (Level Order)

Instinct The answer talks about levels, rows, depth order, "closest to the root" or what you see from a side? Queue the tree and process it one level at a time.

Memory hack Freeze the size, drain the row - read n = queue.size() before the loop and one level never bleeds into the next.

Open the Tree BFS (Level Order) guide →

Approaches

Brute ForceBFS with Queue

Time O(n)Space O(w)

Level-order traversal with a size snapshot. Within a level, keep the previously polled node prev and set prev.next = node; the last node of the level keeps next = null.

Java
public Node connect(Node root) {
    if (root == null) return null;
    Queue<Node> queue = new ArrayDeque<>();
    queue.offer(root);
    while (!queue.isEmpty()) {
        int size = queue.size();
        Node prev = null;
        for (int i = 0; i < size; i++) {
            Node node = queue.poll();
            if (prev != null) prev.next = node;
            prev = node;
            if (node.left != null) queue.offer(node.left);
            if (node.right != null) queue.offer(node.right);
        }
    }
    return root;
}

Straightforward, but the queue holds a whole level — fails the O(1) follow-up.

At a glance

LevelApproachTimeSpace
Brute ForceBFS with QueueO(n)O(w)
BetterDFS with Last-Node-per-DepthO(n)O(h)
OptimalWalk Level via next + Dummy HeadO(n)O(1)
Common pitfalls
  • Assuming a perfect tree (LC 116): left.next = right breaks when children are missing.
  • Not resetting dummy.next → an infinite loop on the last level.
  • BFS: linking the last node of one level to the first node of the next.
Interview tips
  • Start with BFS, then ask: “can the finished level replace the queue?”
  • Draw two levels and show tail stitching children across different parents.
  • Point out the difference from LC 116 (perfect tree) and why gaps matter.
Pattern
Use the already-built structure as the iterator → once a level is linked, walk it like a list to process the next level in O(1) space.
My notes saved in this browser