LeetCode #116 Medium

Populating Next Right Pointers

Populating Next Right Pointers in Each Node is LeetCode 116 (Medium). You get a perfect binary tree: every parent has two children and all leaves sit on the same level. Each node also has a pointer next, which starts as null.

  • Point every node's next at the node to its right on the same level.
  • The last node on each level keeps next = null.
  • Return the root.

The follow-up asks for constant extra space. The recursion stack is allowed and does not count.

Constraints
  • The number of nodes in the tree is in the range [0, 2¹² - 1].
  • -1000 <= Node.val <= 1000
treebfspointers
Open on LeetCode ↗
02

Intuition

Once a level is linked, it is a linked list you can walk with next. That walk can replace the BFS queue for the level below. Stand on each node of the linked level and wire its two children:

  • Same parent: node.left.next = node.right.
  • Different parents: node.right.next = node.next.left, the left child of the node to the right.

The perfect shape is what makes the second link safe: if node.next exists, it sits on the same level as node, so it has a left child too. The root is a finished level of one, so start there and wire each level from the one above.

How to spot this pattern

To connect nodes at the same level is a level-order job. When the links you are building are themselves a way to walk a level, the queue can go: each finished level carries you across while you wire the next.

03

Approach

Try it first

Before reading on, wire the tree level by level with a queue. Then look at the level you just finished: its next pointers already visit it left to right. Use that walk to wire the next level and drop the queue. Aim for O(1) extra space.

1

Keep a pointer to the start of each level

Set leftmost = root. The first node of every level is the left child of the first node above it, so this one pointer is enough to find where each new level begins.

2

Walk the level through its next pointers

Set head = leftmost and move with head = head.next until it is null. The previous round linked this level, so the walk visits every node on it from left to right without any queue.

3

Wire the two children of each node

For each head, link its left child to its right child. Then, if head.next is not null, link its right child to head.next.left. The first link joins siblings; the second joins the children of two neighbouring parents.

4

Drop down a level and stop at the leaves

After the walk, set leftmost = leftmost.left. Stop when leftmost has no left child: that is the leaf level, which was already linked from above and has no children of its own to wire.

04

Code in Python, C++ and Java

▶1class Solution:
▶2 def connect(self, root):
▶3 leftmost = root
▶4 while leftmost and leftmost.left:
▶5 head = leftmost
▶6 while head:
▶7 head.left.next = head.right
▶8 if head.next:
▶9 head.right.next = head.next.left
▶10 head = head.next
▶11 leftmost = leftmost.left
▶12 return root
leftmost1head–null1234567leftmost starts at the root
leftmost1level 0
nodes7
Every next starts as null. The root's level has one node, so it is already a finished linked list: 1 → null. That level will be the rails for wiring the level below it.
leftmost1head1null12345672 → 3: both are children of 1
head1level 0
2.next3same parent
Stand on 1. Its left child 2 and right child 3 are side by side, so link 2 → 3. Both children are reached straight from 1, with no search.
leftmost1head1nullnull12345671 is last on its level → nothing right of 3
head.nextnullend of level 0
3.nextnullnothing to its right
1 has no right neighbour, so there is nothing to the right of its child 3 either. Leave 3's pointer at null: level 1 is now fully linked.
leftmost2head–nullnull1234567level 1 linked → leftmost moves to 2
leftmost2level 1
The walk along level 0 fell off its end. Step down to 2, the first node of level 1. That level is linked now, so it can be walked with next exactly like the one above.
leftmost2head2nullnull12345674 → 5: both are children of 2
head2level 1
4.next5same parent
Stand on 2. Its left child 4 and right child 5 are side by side, so link 4 → 5. Both children are reached straight from 2, with no search.
leftmost2head2nullnull12345675 → 6: across to 3's left child
head.next3set last round
5.next6different parents
2 already points to 3, so 5's right-hand neighbour is 3's left child, 6. The tree is perfect, so that child is sure to exist. This link joins two different subtrees.
leftmost2head3nullnull12345676 → 7: both are children of 3
head3level 1
6.next7same parent
Stand on 3. Its left child 6 and right child 7 are side by side, so link 6 → 7. Both children are reached straight from 3, with no search.
leftmost2head3nullnullnull12345673 is last on its level → nothing right of 7
head.nextnullend of level 1
7.nextnullnothing to its right
3 has no right neighbour, so there is nothing to the right of its child 7 either. Leave 7's pointer at null: level 2 is now fully linked.
leftmost4head–nullnullnull1234567level 2 linked → leftmost moves to 4
leftmost4level 2
The walk along level 1 fell off its end. Step down to 4, the first node of level 2. That level is linked now, so it can be walked with next exactly like the one above.
leftmost4head–nullnullnull12345674 has no children → stop
leftmost4on the leaf level
4 has no left child, so this is the bottom level. Its links were set while walking the level above, and it has no children to wire, so the loop ends.
leftmost–head–nullnullnull1234567every level linked → return root
levels3
extra space2 pointers
Each level now reads left to right through next: 1 → null; 2 → 3 → null; 4 → 5 → 6 → 7 → null. Only leftmost and head were stored, never a queue.
05

Populating next right pointers with BFS

The queue always holds exactly one level when the inner loop starts. Each popped node becomes the next of the node popped just before it, and prev resets to null at the start of every level so no link crosses from one level to the next.

▶1from collections import deque
▶2 
▶3class Solution:
▶4 def connect(self, root):
▶5 if not root:
▶6 return root
▶7 q = deque([root])
▶8 while q:
▶9 prev = None
▶10 for _ in range(len(q)):
▶11 node = q.popleft()
▶12 if prev:
▶13 prev.next = node
▶14 prev = node
▶15 if node.left:
▶16 q.append(node.left)
▶17 q.append(node.right)
▶18 return root
06

Common pitfalls

Linking only siblings

✗ Wrong
head.left.next = head.right
✓ Right
head.left.next = head.right
if head.next:
    head.right.next = head.next.left

On [1,2,3,4,5,6,7], node 5 has no sibling to its right, so it keeps null instead of pointing to 6. The level falls apart into pairs, and on a deeper tree the next walk stops at 5 and never wires 6's children.

Looping while leftmost is not null

✗ Wrong
while leftmost:
✓ Right
while leftmost and leftmost.left:

The loop then reaches the leaf level and runs head.left.next on a node with no children, which crashes. A single-node tree [1] fails on the very first step.

07

Edge cases

Empty tree, []

leftmost is null, so the loop never runs and null is returned.

Only the root, [1]

The root has no left child, so the loop never runs. The root's next was already null, which is correct.

08

Complexity

Time
O(n)
Space
O(1)
Each node is head once and makes at most two pointer writes. Only leftmost and head are stored, so the extra space stays constant no matter how deep the tree is.
09

Populating Next Right Pointers FAQ

What changes in Populating Next Right Pointers II?

LeetCode 117 drops the perfect-tree promise, so head.next.left may not exist and a child may be missing. Keep a dummy node at the start of the next level and a tail pointer; while walking the current level, append each child that exists to tail. It is still O(n) time and O(1) space, and it also solves this problem.

Is the recursive solution also O(1) space?

The problem says the recursion stack does not count, so yes for grading. A recursive version makes the same two links at each node and then recurses into both children. The stack still holds one frame per level, at most 12 here, so it is O(log n) in real memory.