Perfect tree — recursive

Node connect(Node root) {
  if (root == null || root.left == null) return root;
  root.left.next = root.right;
  root.right.next = root.next == null ? null : root.next.left;
  connect(root.left); connect(root.right);
  return root;
}
Advertisement

General tree — O(1) space

Node connect(Node root) {
  Node level = root;
  while (level != null) {
    Node dummy = new Node(), tail = dummy;
    for (Node cur = level; cur != null; cur = cur.next) {
      if (cur.left != null) { tail.next = cur.left; tail = tail.next; }
      if (cur.right != null) { tail.next = cur.right; tail = tail.next; }
    }
    level = dummy.next;
  }
  return root;
}
Advertisement

Why O(1)

Once upper level is linked, use it to build lower level's next pointers. No queue needed.

BFS approach

Standard queue-based BFS. O(W) space. Simpler but worse space.