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

Populating Next Right Pointers in Each Node

MediumBreadth-first search

You are given the root of a perfect binary tree: every parent has exactly two children and all leaves sit on the same level. Besides left and right, each node has a next field, and all of them start out null.

Point every node's next at the node directly to its right on the same level. The rightmost node of each level keeps next = null. 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 = [5, 3, 8, 1, 4, 7, 9]
Output: [5, #, 3, 8, #, 1, 4, 7, 9, #]
Why:    4 and 7 have different parents but are neighbours
2 more examples and the constraints

Example 2

Input:  root = [-6]
Output: [-6, #]
Why:    one node, alone on its level

Example 3

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

Constraints

  • 0 ≤ number of nodes ≤ 4,095, and the tree is perfect
  • −1,000 ≤ node value ≤ 1,000
  • 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 4,095 nodesVerdict
BFS, one level at a timeO(n)
Passes; O(n) queue
Link the level below from aboveO(n)
Best; O(1) extra space

n = number of nodes. Both touch every node once; the second needs no queue.

Edge cases to test

  • Empty tree. Return null; the loop never starts.
  • One node. It has no children, so nothing is linked and its next stays null.
  • Cousins. In Example 1, 4 (under 3) must link to 7 (under 8).
  • Right edge. The last node of every level keeps null: only link cousins when node.next exists.

Common mistakes

  • Linking only siblings, so 4 never reaches 7 across the two parents.
  • Reading node.next.left without checking that node.next exists.
  • Looping down while leftmost is not null and then touching leftmost.left.next on a leaf.

How to talk through it

  1. 1Clarify. Is the tree always perfect? Can it be empty? Does the recursion stack count as extra space?
  2. 2Give the BFS. Link nodes as they leave the queue, one level per round; O(n) extra space at the bottom level.
  3. 3Use the links you built. A linked level is a list: walk it with next instead of a queue.
  4. 4Code the two links. Sibling link, then cousin link when node.next exists; move down by leftmost.left.
  5. 5Test out loud. Run an empty tree, one node and the cousin link in a three-level tree.
Was this problem useful?Your vote tells us what to improve next.
Found a bug in our code, or something unclear?