Description

Populating Next Right Pointers in Each Node

You are given a perfect binary tree where all leaves are on the same level, and every parent has two children. The binary tree has the following definition:

struct Node {
  int val;
  Node *left;
  Node *right;
  Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.
Initially, all next pointers are set to NULL.

Example 1:

Input: root = [1,2,3,4,5,6,7]
Output: [1,#,2,3,#,4,5,6,7,#]
Explanation: Given the above perfect binary tree (Figure A), your function should populate each next pointer to point to its next right node, just like in Figure B. The serialized output is in level order as connected by the next pointers, with ’#’ signifying the end of each level.

Example 2:
Input: root = []
Output: []

Constraints:

  • The number of nodes in the tree is in the range [0, 212 - 1].
  • -1000 <= Node.val <= 1000

Follow-up:

  • You may only use constant extra space.
  • The recursive approach is fine. You may assume implicit stack space does not count as extra space for this problem.

Approach 1: Pointer Iteration using Established next Pointers ( Time, Space)

Intuition

Since this is a perfect binary tree, we can use the next links established on the current level to set up the next links for the children on the next level down—eliminating the need for extra queue memory:

  1. Maintain a leftmost pointer to track the beginning of each level, starting at root.
  2. Iterate horizontally across the current level using pointer curr:
    • Same Parent Connection: Point curr.left.next directly to curr.right.
    • Cross Parent Connection: If curr.next != null, point curr.right.next to curr.next.left.
  3. Advance curr = curr.next until the level end is reached, then drop down to leftmost = leftmost.left.
class Solution {
    public Node connect(Node root) {
        if (root == null) return null;
 
        Node leftmost = root;
 
        // Loop until reaching leaf level
        while (leftmost.left != null) {
            Node curr = leftmost;
 
            while (curr != null) {
                // Connection 1: Left child -> Right child of same parent
                curr.left.next = curr.right;
 
                // Connection 2: Right child -> Left child of next parent
                if (curr.next != null) {
                    curr.right.next = curr.next.left;
                }
 
                // Move horizontally across the current level
                curr = curr.next;
            }
 
            // Move down to the next level
            leftmost = leftmost.left;
        }
 
        return root;
    }
}
 

Complexity

  • Time Complexity: — Every node in the tree is visited once.
  • Space Complexity: — Modifies tree pointers in-place using constant auxiliary variables.

Approach 2: Level-Order BFS ( Time, Space)

Intuition

Process the tree level by level using a queue:

  1. Push root into an ArrayDeque.
  2. For each level, determine levelSize = queue.size().
  3. Loop i from 0 to levelSize - 1:
    • Poll current node curr.
    • If i < levelSize - 1, set curr.next = queue.peek() (since the queue’s front element is the next node in the same level).
    • Push non-null left and right children into the queue.
import java.util.ArrayDeque;
import java.util.Deque;
 
class Solution {
    public Node connect(Node root) {
        if (root == null) return null;
 
        Deque<Node> queue = new ArrayDeque<>();
        queue.offer(root);
 
        while (!queue.isEmpty()) {
            int levelSize = queue.size();
 
            for (int i = 0; i < levelSize; i++) {
                Node curr = queue.poll();
 
                // Connect to the next node in queue if not the last item in level
                if (i < levelSize - 1) {
                    curr.next = queue.peek();
                }
 
                if (curr.left != null) queue.offer(curr.left);
                if (curr.right != null) queue.offer(curr.right);
            }
        }
 
        return root;
    }
}
 

Complexity

  • Time Complexity: — Each node is pushed and polled from the queue once.
  • Space Complexity: — Space required to store the maximum level width in the queue (up to leaf nodes).

Easy Memory Rule

“Inner connection: curr.left.next = curr.right Outer cross connection: curr.right.next = curr.next.left!”