SDE & MLE Prep

117. Populating Next Right Pointers in Each Node II

Problem

In any binary tree, set each node's next pointer to the node immediately to its right on the same level, or null if it is the rightmost.

Example: [1,2,3,4,5,null,7] → levels linked as 1→null, 2→3→null, 4→5→7→null

Constraints: follow-up: O(1) extra space.

Arbitrary tree. Walk the current level through its next pointers while building the next level's chain with a dummy head + tail pointer. O(1) extra space.

Complexity: O(n) time, O(1) space.

class Node:  # provided by LeetCode
    def __init__(self, val=0, left=None, right=None, next=None):
        self.val, self.left, self.right, self.next = val, left, right, next

class Solution:
    def connect(self, root: "Node") -> "Node":
        level = root
        while level:
            dummy = tail = Node(0)
            node = level
            while node:
                for child in (node.left, node.right):
                    if child:
                        tail.next = tail = child
                node = node.next
            level = dummy.next
        return root