LeetCode #116 Medium

Populating Next Right Pointers

In a perfect binary tree, point every node's next at its right neighbour on the same level.

treebfspointers
Open on LeetCode ↗
02

Intuition

Once a level is linked, it becomes a linked list you can walk to wire the level below — no queue needed. A node's children link as left→right; the gap across subtrees bridges via the parent's next: node.right.next = node.next.left.

How to spot this pattern

The O(1)-space trick: once a level is threaded by next pointers, it acts as a linked list you can walk to wire the level below — no queue needed. Whenever a structure already contains the traversal order you were about to build a container for, use the structure. This only works because the tree is perfect, which guarantees every node has both children.

03

Approach

1

Use the level above as rails

Walk level L via next pointers while connecting level L+1 — O(1) extra space, unlike BFS's queue.

2

Two wire types

Same parent: left.next = right. Across parents: right.next = parent.next.left (exists because the tree is perfect).

3

Descend leftmost

After finishing a level, drop to its leftmost node and repeat until leaves.

04

Solution & live demo

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
05

Common pitfalls

Using a BFS queue

✗ Wrong
q = deque([root])
while q:
    for _ in range(len(q)): ...
✓ Right
while leftmost and leftmost.left:
    head = leftmost
    while head: ...

Correct, but the follow-up asks for constant extra space and a queue holds up to n/2 nodes. The next pointers you just wired on the level above give you the same traversal for free.

Forgetting the cross-node link

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

Wiring only within a parent leaves the level broken into disconnected pairs, so the next iteration can't walk across it. The gap between one parent's right child and the next parent's left child has to be bridged too.

Looping while leftmost alone is non-null

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

On the last level there are no children to wire, and head.left.next raises. Checking for a left child confirms another level exists before trying to thread it.

06

Edge cases

Non-perfect trees (problem 117)

parent.next.left may not exist — needs a scan for the next available child; this version relies on perfection.

Empty tree

Return immediately.

07

Complexity

Time
O(n)
Space
O(1)
Prior level serves as the queue.