Populating Next Right Pointers in Each Node II (LeetCode 117): Solution and Explanation

Medium
Linked list
Tree
Depth First search
Breadth First search
Binary tree

Given any binary tree whose nodes have a next field, point every node's next at the node to its right on the same level, or null for the last node. Unlike part I, children may be missing anywhere, so a neighbor can be a distant cousin.

Intuition

A level-order BFS with a queue solves it directly: link each node to the one dequeued after it on the same level. That costs O(width) memory, and the follow-up asks for constant space.

Once a level is linked, it is a linked list. Walking it with next visits every parent on that level from left to right, which is exactly the order their children appear on the level below.

So while walking level L, build level L+1 like appending to a linked list: keep a tail pointer prev, set prev.next = child for each child met, and remember the first child as the start of the next walk.

Approach: Walk by next, thread with a tail pointer

  1. Set level_start = root.
  2. For each level, set cur = level_start, prev = None and clear level_start.
  3. For each non-null child of cur (left, then right): if prev exists set prev.next = child, otherwise record level_start = child. Then prev = child.
  4. Move cur = cur.next until the level ends, then repeat from the recorded level_start. Stop when no child was found.

Step-by-step example

root = [1,2,3,4,5,null,7]
  1. Level 0 is just node 1. Its children 2 and 3 are threaded: level_start = 2, then 2.next = 3.
  2. Walk level 1 from 2. Node 2's children: 4 becomes level_start, then 4.next = 5, prev = 5.
  3. cur = 2.next = 3. Node 3 has no left child, so skip it. Its right child 7: 5.next = 7, jumping the gap.
  4. 3.next is null, so level 1 is done. Walk level 2 from 4: no node has children, so level_start stays null and the loop ends.
  5. Reading next pointers level by level gives [1,#,2,3,#,4,5,7,#].

Code: Python, Java, C++

1class Solution:
2    def connect(self, root: 'Optional[Node]') -> 'Optional[Node]':
3        level_start = root
4        while level_start:
5            cur = level_start
6            prev = None
7            level_start = None
8            while cur:
9                for child in (cur.left, cur.right):
10                    if not child:
11                        continue
12                    if prev:
13                        prev.next = child
14                    else:
15                        level_start = child
16                    prev = child
17                cur = cur.next
18        return root
Press play on the visualizer and the running line lights up here.

Time and space complexity

Time

O(n)

Every node is visited once as a parent (cur) and once as a child.

Space

O(1)

Only the pointers level_start, cur and prev are kept; the next pointers being built replace the queue.

Other approaches

BFS with a queue (time O(n), space O(width))

Process the tree level by level with a queue, linking each node to the next node popped from the same level. Simple, but the queue can hold a whole level.

Dummy head per level (time O(n), space O(1))

The same walk, but the level below starts at a dummy node so the first append needs no special case: tail = dummy, tail.next = child. After the walk, the next level starts at dummy.next.

Recursion right to left (time O(n^2) worst case, space O(h))

Connect a node's children first, finding the right child's neighbor by scanning the parent's next chain for the first child, then recurse into the right subtree before the left. Easy to get wrong if the left subtree is processed first.

Common mistakes

  • Reusing the part I trick node.right.next = node.next.left. In a non-perfect tree the next parent may have no left child, or no children at all.
  • Forgetting to reset prev to null at the start of each level, which links the last node of one level to the first node of the next.
  • Moving down via level_start.left. If the first node of a level has no children, the next level starts somewhere else; record the first child met instead.
  • Recursing into the left subtree before the right one, so next pointers needed to find cousins are not set yet.

Frequently asked questions

How is this different from part I?

Part I guarantees a perfect binary tree, so a node's neighbor is always its sibling or its parent's next node's left child. Here children can be missing anywhere, so the neighbor must be found by scanning along the parent level.

Why does walking by next give children in the right order?

The parent level is linked left to right, and each parent's children sit left to right under it, so visiting parents in order and taking left before right lists the child level from left to right.

What does '#' mean in the output?

The output reads each level through next pointers and writes '#' when it reaches a null next, marking the end of that level.