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

Solve LeetCode 117: Populating Next Right Pointers in Each Node II in Python with a level linked-list construction approach. The key is to make the state invariant explicit, so the implementation and complexity follow naturally.

This guide paraphrases the task and does not reproduce LeetCode’s prompt. Use the official page for the complete statement, examples, constraints, and submission runner.

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

What the problem is testing

Use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain.

Algorithm

  1. Use the current level’s next pointers to scan horizontally while a dummy tail builds the next level’s next chain.
  2. Maintain this invariant: The dummy chain contains every discovered child on the next level in left-to-right order.
  3. Continue until every input item or reachable state has been resolved, then return the accumulated result.

Python solution

LeetCode provides the list, tree, or graph node definition used by the method.

from collections import Counter, defaultdict, deque, OrderedDict
import random

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

Why this is correct

The proof follows the maintained state: The dummy chain contains every discovered child on the next level in left-to-right order. Each iteration preserves that claim while permanently resolving at least one position, node, interval, or search state. When the loop or recursion ends, every candidate required by the problem has therefore been included or ruled out, so the returned value is correct.

Complexity

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

Edge cases

Sparse levels and missing left or right children require independent child checks.

Tested reference code

This implementation is included in the site’s downloadable 100-solution Python library. The complete suite compiles every solution and runs a behavioral assertion for every problem before publication.


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