sagelearnai

Populating Next Right Pointers in Each Node

Difficulty: Medium · Pattern: Trees & BST · LeetCode #116

You are given a perfect binary tree: every internal node has two children and all leaves are on the same level. Each node has an extra pointer next. Set every next to the node immediately to its right on the same level, or null for the last node of a level. Return the root.

The tests walk the levels through your next pointers and print each level.

Examples

text
        1 → null
       / \
      2 → 3 → null
     / \ / \
    4→5→6→7 → null
[1,2,3,4,5,6,7]  →  [[1],[2,3],[4,5,6,7]]

Hints

  1. BFS with a queue works, but uses O(width) memory. Can you do it in O(1)?
  2. Once level L is linked, you can walk across it with next. Use that walk to link level L+1.

Approach

Walk each level using the next pointers you've already set, and wire up the children:

text
leftmost = root
while leftmost.left:              # while there is a next level
    head = leftmost
    while head:
        head.left.next = head.right               # siblings
        if head.next:
            head.right.next = head.next.left      # cousins across parents
        head = head.next
    leftmost = leftmost.left

The tree being perfect guarantees that left and right both exist below every internal node. LeetCode 117 drops that guarantee, and you then track a dummy head for the next level.

Complexity

Time: O(n). Space: O(1).

Python solution
def connect(root):
    leftmost = root
    while leftmost and leftmost.left:
        head = leftmost
        while head:
            head.left.next = head.right
            if head.next:
                head.right.next = head.next.left
            head = head.next
        leftmost = leftmost.left
    return root
JavaScript solution
function connect(root) {
  let leftmost = root;
  while (leftmost && leftmost.left) {
    let head = leftmost;
    while (head) {
      head.left.next = head.right;
      if (head.next) head.right.next = head.next.left;
      head = head.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}