SDE & MLE Prep

116. Populating Next Right Pointers in Each Node

Problem

In a perfect binary tree (every level full), set each node's next pointer to the node immediately to its right on the same level, or null for the rightmost node.

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

Constraints: follow-up: O(1) extra space (recursion stack doesn't count).

Perfect tree → use the already-built next pointers of level i to wire level i+1: left.next = right, right.next = node.next.left. 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: "Optional[Node]") -> "Optional[Node]":
        leftmost = root
        while leftmost and leftmost.left:
            node = leftmost
            while node:
                node.left.next = node.right
                if node.next:
                    node.right.next = node.next.left
                node = node.next
            leftmost = leftmost.left
        return root