Populating Next Right Pointers in Each Node (LeetCode 116): Solution and Explanation
Each node of a perfect binary tree has an extra next pointer. Set it so that every node points to the node immediately to its right on the same level, and the rightmost node of each level points to null.
Watch it run step by step
Try your own input and write the code →Intuition
The phrase same level is the clue. Whenever a tree question is about how nodes relate within a level, level-order traversal with a queue is the first tool to reach for, because a queue hands you the nodes of a level in left to right order.
The standard BFS trick is to record the queue's length at the start of each round. That number is exactly how many nodes belong to the current level, since all of them were enqueued during the previous round and none of the next level has been added yet. While processing those nodes one by one, the node that comes right after the current one in the queue is its right neighbor.
So when you pop a node at position i within its level, the next node is sitting at the front of the queue, queue[0]. If i is not the last position in the level, point node.next at it. For the last node you do nothing, because next already starts as null, and skipping it avoids wrongly linking a level's last node to the first node of the next level.
This approach does not actually rely on the tree being perfect, which makes it a good general tool. The perfect-tree guarantee only matters if you want the O(1) space version, which walks the next pointers of the level above instead of using a queue.
Approach: Level-order BFS with a queue
- If
rootisNone, returnNone. - Put the root into a deque and loop while the queue is not empty.
- Store
length = len(queue), the number of nodes on the current level. - For each index
ifrom 0 tolength - 1, pop a node from the left of the queue. - If
i < length - 1, setnode.next = queue[0], which is the next node on the same level. - Append the node's left and right children to the queue for the next round, then return
rootonce every level is processed.
Step-by-step example
root = [1,2,3,4,5,6,7]
- The queue starts as [1], so the level length is 1. Node 1 is the last on its level, so its
nextstays null. Its children make the queue [2,3]. - Level length 2. Pop 2 at index 0, and the front of the queue is 3, so 2.next = 3. Enqueue 4 and 5, giving [3,4,5].
- Pop 3 at index 1, which is the last index, so 3.next stays null. Enqueue 6 and 7, giving [4,5,6,7].
- Level length 4. Pop 4 and link it to 5, pop 5 and link it to 6, pop 6 and link it to 7. Node 7 is last, so it stays null.
- The leaves have no children, so the queue empties and the levels read 1 then null, 2 then 3 then null, and 4, 5, 6, 7 then null.
Code: Python, Java, C++
1class Solution:
2 def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
3 if not root:
4 return None
5
6 queue = collections.deque([root])
7
8 while queue:
9 length = len(queue)
10 for i in range(length):
11 node = queue.popleft()
12 if i < length - 1:
13 node.next = queue[0]
14
15 if node.left:
16 queue.append(node.left)
17 if node.right:
18 queue.append(node.right)
19
20 return root1class Solution {
2 public Node connect(Node root) {
3 if (root == null) return null;
4
5 Queue<Node> queue = new LinkedList<>();
6 queue.add(root);
7
8 while (!queue.isEmpty()) {
9 int length = queue.size();
10 for (int i = 0; i < length; i++) {
11 Node node = queue.poll();
12
13 if (i < length - 1) {
14 node.next = queue.peek();
15 }
16
17 if (node.left != null) queue.add(node.left);
18 if (node.right != null) queue.add(node.right);
19 }
20 }
21
22 return root;
23 }
24}1class Solution {
2public:
3 Node* connect(Node* root) {
4 if (!root) return nullptr;
5
6 queue<Node*> q;
7 q.push(root);
8
9 while (!q.empty()) {
10 int length = q.size();
11 for (int i = 0; i < length; i++) {
12 Node* node = q.front();
13 q.pop();
14
15 if (i < length - 1) {
16 node->next = q.front();
17 }
18
19 if (node->left) q.push(node->left);
20 if (node->right) q.push(node->right);
21 }
22 }
23
24 return root;
25 }
26};Time and space complexity
O(n)
Every node is enqueued and dequeued exactly once, and setting its pointer takes constant time.
O(n)
The queue holds at most one full level plus some children. In a perfect tree the last level contains about n / 2 nodes, so the queue grows to O(n).
Other approaches
Use the next pointers already built (time O(n), space O(1))
Start at the leftmost node of each level. For every node on that level, link node.left.next = node.right, and if node.next exists link node.right.next = node.next.left. Then move down to the leftmost node of the next level. This relies on the tree being perfect and needs no queue.
Recursive DFS (time O(n), space O(log n))
Recursively connect left.next = right and right.next = next.left at each node, then recurse into both children. It is short, but the call stack uses O(log n) space for a perfect tree.
Common mistakes
- Reading
len(queue)inside the loop instead of capturing it once. The queue grows as children are appended, so the level boundary gets lost. - Linking the last node of a level to
queue[0], which at that moment is the first node of the next level. - Assigning
nextbefore popping, so each node points to itself instead of its neighbor. - Using the O(1) trick on a tree that is not perfect. That version assumes both children exist everywhere above the leaves.
Frequently asked questions
Can you solve Populating Next Right Pointers with O(1) space?
Yes, because the tree is perfect. Walk each level using the next pointers you already set on it, and use them to connect the children below. You only need a pointer to the leftmost node of the current level.
Does the BFS solution work if the tree is not perfect?
Yes. The queue approach never assumes both children exist, so it also solves the follow-up version for arbitrary binary trees. Only the constant-space trick depends on the perfect shape.
Why is the queue's length taken at the start of each level?
At that moment the queue holds exactly the nodes of one level. Saving the length lets you process that many nodes and know which one is last, even though children are being added to the back as you go.