LeetCode 117: Populating Next Right Pointers in Each Node II — Python Solution

LeetCode 117: Populating Next Right Pointers in Each Node II is a Medium binary tree general problem. This Python walkthrough develops a level linked-list construction solution, ties every code decision to a concrete invariant, and includes the regression check used before publication.

This independent guide paraphrases the task rather than reproducing LeetCode’s prompt. Use the official page for the exact statement, examples, constraints, and submission runner.

DifficultyMedium
TopicBinary Tree General
Reusable patternlevel linked-list construction
ComplexityO(n) time and O(1) extra space

Recognizing the pattern

Tree recursion works when the return value has one precise meaning for every subtree; the parent can then combine child results locally.

For this problem specifically, use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain. The invariant worth writing beside the code is: The dummy chain contains every discovered child on the next level in left-to-right order.

Step-by-step algorithm

  1. Identify the input state consumed by connect(root) and initialize the data required by the level linked-list construction pattern.
  2. Use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain.
  3. After each update, verify the page’s central invariant: The dummy chain contains every discovered child on the next level in left-to-right order.
  4. Finish only after the boundary behavior is covered: Sparse levels and missing left or right children require independent child checks.

Python solution

LeetCode supplies the list, tree, or graph node class referenced by this method. The downloadable test suite includes compatible local node definitions so the implementation can also run outside the judge.

class Solution:
    def connect(self, root):
        current = root
        while current:
            dummy = tail = Node(0)
            while current:
                if current.left:
                    tail.next = current.left; tail = tail.next
                if current.right:
                    tail.next = current.right; tail = tail.next
                current = current.next
            current = dummy.next
        return root

Reading the implementation

The main entry point is connect(root). The named working state includes current, dummy; those variables make the level linked-list construction state visible instead of hiding it in incidental control flow.

The implementation uses 2 loops with separate responsibilities, so preprocessing and the main traversal can each stay linear in their own input. In concrete terms, use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain.

Correctness argument

Base case. Empty or terminal subproblems return a result that already satisfies the claim for that smallest state.

Inductive step. Use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain. Assuming child or smaller states are correct, the current call combines only results allowed by the problem, so the dummy chain contains every discovered child on the next level in left-to-right order.

Conclusion. Every recursive call reduces the remaining state. The base cases terminate, and induction carries the invariant back to the original input, establishing the returned answer.

Complexity and trade-offs

O(n) time and O(1) extra space. The auxiliary-space figure excludes the returned output unless the output itself is the structure being built.

An explicit stack avoids recursion-depth limits, but it must carry the same state that recursive call frames provide automatically. That comparison is useful in an interview because it explains why the final implementation is preferable, not merely that it passes.

Regression check

The published implementation belongs to a 100-problem suite that is compiled and exercised behaviorally before deployment.

One reference assertion from that suite is shown below. It targets the normal path while the edge conditions in the next section cover the failure-prone boundaries.

nr=Node(1,left=Node(2),right=Node(3)); Solution().connect(nr); assert nr.left.next is nr.right

Common mistakes and edge cases

  • Problem-specific boundary: Sparse levels and missing left or right children require independent child checks.
  • Pattern-level pitfall: Write the empty-subtree result first and keep returned subtree information separate from any global answer updated at a node.
  • Invariant check: after every update, confirm that the dummy chain contains every discovered child on the next level in left-to-right order.

Interview review checklist

  • Explain why level linked-list construction matches the structure of this input.
  • State the invariant in one sentence before tracing code: The dummy chain contains every discovered child on the next level in left-to-right order.
  • Derive O(n) time and O(1) extra space from how many times each element or state is visited.
  • Test the boundary explicitly: Sparse levels and missing left or right children require independent child checks.

Browse the searchable 100 LeetCode Python Solutions hub. Previous: 106. Construct Binary Tree from Inorder and Postorder Traversal · Next: 114. Flatten Binary Tree to Linked List