Skip to problem
←

Populating Next Right Pointers in Each Node

Medium 0 attempts

Given the root of a perfect binary tree, set each node's next pointer to the node immediately to its right on the same level. Set the rightmost node's next to null on every level.

A perfect binary tree has exactly two children at every internal node, and all leaves are at the same depth. All next pointers are initially null.

Modify the original nodes and return the original root. Preserve their values and left/right child links. An empty tree returns null. Use constant extra space.

For [1, 2, 3, 4, 5, 6, 7], the links are 1 → null, 2 → 3 → null, and 4 → 5 → 6 → 7 → null. In particular, 5 must link to 6 even though they have different parents.

The input uses a level-order array. Your function receives nodes with val, left, right, and next properties. The displayed output lists each level by following its next pointers; return the root, not those arrays.

Function contract

Implement connect(root). Trees use level-order arrays with null for missing children. The editor passes nodes with val, left, and right properties; [] becomes null.

Output: Return the original root after setting next pointers. The runner displays the values reached across each level.

Example 1

Input
root = [1,2,3,4,5,6,7]
Output
[[1],[2,3],[4,5,6,7]]

Example 2

Input
root = []
Output
[]
Visual Aid
Connect across parents, too
Next pointers across tree levelsSolid lines show child links. Dashed arrows connect 2 to 3, and 4 to 5 to 6 to 7. The 5 to 6 arrow crosses between parents.1234567Dashed arrows = next links · rightmost nodes point to null

The next link from 5 to 6 joins two sibling subtrees at the same level.

Constraints
  • 0 <= number of nodes <= 2^12 - 1
  • -1000 <= Node.val <= 1000
  • The tree is perfect, and every next pointer initially equals null.

Level-by-Level Using Next Pointers

The current level's next links let us traverse it without a queue. For each parent, connect its left child to its right child. If the parent has a next neighbor, connect its right child to that neighbor's left child. Otherwise its right child remains the last node on the next level and points to null.

After finishing a level, move to its leftmost child. The root's level is already linked because its only node points to null; each completed level establishes the links needed for the next traversal. The perfect-tree guarantee ensures that both children exist whenever the level has children.

javascript
function connect(root) {
  if (!root) return root;
  let leftmost = root;
  while (leftmost.left) {
    let curr = leftmost;
    while (curr) {
      curr.left.next = curr.right;
      curr.right.next = curr.next ? curr.next.left : null;
      curr = curr.next;
    }
    leftmost = leftmost.left;
  }
  return root;
}

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

Loading discussion…

Saved in this browser only. Private to you.

JavaScript