Populating Next Right Pointers in Each Node II
Problem Statement
You are given a binary tree. It is not necessarily perfect: a node can have two children, one child, or none. Each node has a next pointer, and all of them start as null.
Set every next pointer to the node on its right, on the same level. If there is no node on the right, set it to null. Return the root.
The root of a binary tree (it can be empty). Each node has val, left, right and next.
The same root, with every next pointer filled in.
The output lists the nodes level by level, following the next pointers, and # marks the end of each level. Node 5 points to node 7, even though their parents (2 and 3) are different. Node 3 has no left child, so the level below does not start under it.
An empty tree has no nodes, so there is nothing to set.
- β’ The number of nodes is in the range [0, 6000]
- β’ β100 β€ Node.val β€ 100
- β’ Follow-up: can you use only constant extra space?
Pattern Recognition Clues
Recognising these key signals in the problem description immediately identifies the pattern:
Approach Complexity Ladder
BFS with a queue; link each popped node to the front of the queue unless it is the last of its round
Walk the level with next and append each node's children to the level below, using a dummy head and a tail
The same idea as LC 116: go level by level with a queue. Each popped node points to the next node popped in the same round. The last node of each round keeps next = null. Gaps do not matter, because the queue only holds the nodes that exist.
Recognition rule for this sub-pattern:
Unlock Complete Visual Walkthrough & Optimal C++
The interactive animated dry-run player, optimized C++ implementation, state invariant derivations, and edge-case breakdown for this question are part of Brute2Best Pro. The anchor question of every sub-pattern is completely free.
First anchor question per pattern, Part 1 LLD & Module 1 C++ basics are 100% Free forever.
How this concept connects to System Design & C++ Systems
Top engineering interviews test whether you understand how algorithms like Tree BFS translate into production architectures and low-level memory mechanics.
Foundations: Object-Oriented Principles in C++23
Class invariants, pure virtual interfaces, and RAII smart pointers.
Food Delivery System (Zomato Architecture)
Real-world machine coding application of algorithms and design patterns.
Pointers vs References Deep Dive
Pointer arithmetic and memory layout under the hood.
Virtual Method Table (vtable) & Memory Layout
Polymorphism, vptr overhead, and multiple inheritance in memory.