Skip to content
Problem 117 · LeetCode 117(opens in a new tab)

Populating Next Right Pointers in Each Node II

MediumBreadth-first search

You are given the root of a binary tree. Besides left and right, every node has a next field, and all of them start out null.

Set each node's next to the node directly to its right on the same level. The rightmost node of a level keeps next = null. The tree is not necessarily full, so a node's right neighbour may have a different parent, with gaps in between. Return the root.

In the examples, the output lists each level by following next from its leftmost node, with # marking the end of a level.

Example 1

Input:  root = [6, 2, 9, 1, null, null, 8]
Output: [6, #, 2, 9, #, 1, 8, #]
Why:    1 and 8 have different parents but are neighbours
2 more examples and the constraints

Example 2

Input:  root = [3, null, 5]
Output: [3, #, 5, #]
Why:    each level has one node, so every next stays null

Example 3

Input:  root = []
Output: []
Why:    there are no nodes to link

Constraints

  • 0 ≤ number of nodes ≤ 6,000
  • −100 ≤ node value ≤ 100
  • Follow-up: use O(1) extra space (recursion stack does not count)

Your turn first

Have a go on paper or in your own editor, then reveal the approaches from the simplest up.

Try it on LeetCode(opens in a new tab)
  1. BFS, one level at a timeO(n)

The idea in one sentence

The pattern, how to spot it, and the best complexity.

Side by side

ApproachTimeRelative work for 6,000 nodesVerdict
BFS, one level at a timeO(n)
Passes; O(w) queue
Walk a level by its linksO(n)
Best; O(1) extra space

n = number of nodes, w = widest level. Both touch every node once.

Edge cases to test

  • Empty tree. Return null; both loops simply never run.
  • One node. Its next stays null.
  • Neighbours with different parents. In [6, 2, 9, 1, null, null, 8], 1 must link to 8.
  • Next level starts late. In [1, 2, 3, null, null, 4, 5], level 2 starts under 3, not 2.
  • A chain. One node per level: every next is null.

Common mistakes

  • Assuming the tree is perfect and linking node.right.next = node.next.left, which breaks on gaps.
  • Taking the next level's start as head.left, when the leftmost node may have no children.
  • Linking the last node of a level to the first node of the next level.

How to talk through it

  1. 1Clarify. Can the tree be empty? Is it perfect? Does the recursion stack count as extra space?
  2. 2Give the BFS. Link nodes as they come out of the queue, one level per round; O(w) space.
  3. 3Notice the lists. A linked level is a list you can walk without a queue.
  4. 4Code the dummy walk. Append children behind a dummy; its next is the next head.
  5. 5Test out loud. Run an empty tree, a chain and a tree with gaps between cousins.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?