Connect All Siblings of a Binary Tree

Wire every node's `next` pointer to the next node in level-order across the entire tree.

Medium
Time O(n) Space O(1)
4 min read
tree bfs linked-list

Problem#

Given a general binary tree (not necessarily perfect), set each node’s next pointer to the node that immediately follows it in level-order. The last node of each level points to the first node of the next level — there is one continuous chain across the entire tree. This is an curriculum variant of the LeetCode “Populating Next Right Pointers” series.

Examples#

  • Tree [1,2,3,4,null,5,6] → next chain 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> null.
  • Single node [1]1 -> null.

Constraints#

  • 0 <= n <= 10^4.

Hints#

Hint
BFS the tree, hold the previous node, and just wire prev->next = current on each pop.

Approach#

Standard BFS with a queue. Maintain a prev pointer initialized to nullptr; for each dequeued node cur, set prev->next = cur (if prev) and update prev = cur. Final node naturally keeps next = nullptr from construction.

Solution#

Connect All Siblings of a Binary Tree
struct Node {
int val;
Node *left, *right, *next;
Node(int v) : val(v), left(nullptr), right(nullptr), next(nullptr) {}
};
class Solution {
public:
Node* connectAll(Node* root) {
if (!root) return nullptr;
queue<Node*> q;
q.push(root);
Node* prev = nullptr;
while (!q.empty()) {
Node* cur = q.front(); q.pop();
if (prev) prev->next = cur;
prev = cur;
if (cur->left) q.push(cur->left);
if (cur->right) q.push(cur->right);
}
return root;
}
};

Editorial#

Unlike LeetCode 116/117 (which connect only within a level), here we want one continuous level-order linked list. Plain BFS produces nodes in exactly that order, so we just chain consecutive dequeues. No size snapshot needed.

Complexity#

  • Time: O(n).
  • Space: O(width) for the queue — O(n) worst case.

Concept revision#

Search ESC

Keyboard shortcuts

Shortcuts are disabled while typing in inputs.