AAlgoLoopSpaced repetition for LeetCode
MEDIUMBFS / DFSLeetCode ↗

Populating Next Right Pointers in Each Node

The key idea

It is a perfect binary tree, so once a level is fully linked you can walk that level left to right via the next pointers you just set, and use them to stitch the children of the level below for free — no queue needed.

Problem

You are given a perfect binary tree where all leaves are on the same level and every parent has two children. Each node has an extra next pointer that should point to its next right node on the same level. If there is no next right node, next should be set to null.

Initially, all next pointers are null. Populate every next pointer so the tree's levels become singly linked lists from left to right. Return the modified tree's root.

The rightmost node on each level has no node to its right, so its next stays null. The challenge is to wire the whole tree using only constant extra space — the next pointers you set on one level give you a free way to traverse it and connect the level below.

Constraints

Examples

Input: root = [1,2,3,4,5,6,7] Output: [1,#,2,3,#,4,5,6,7,#]
Input: root = [] Output: []

Complexity

Time: O(n) Space: O(1)

See the full solution

410310
Step-by-step visualization
Start free →

More BFS / DFS problems