ExamAdda Logo

Populating Next Right Pointers in Each Node II

Easy

Given a binary tree where every node has:

val left right next

 

Populate each node's next pointer so that it points to the next node on the same level.

If there is no node to the right, set:

next = NULL

 

Unlike Problem 116, this tree does not have to be perfect.

Example Tree

     1      

    / \    

   2   3     

  / \   \

 4   5   7

 

After connecting:

1 → NULL 2 → 3 → NULL 4 → 5 → 7 → NULL

Example 1

Input

root = [1,2,3,4,5,null,7]

Output

[1,#,2,3,#,4,5,7,#]

Explanation

The tree is:

     1   

    / \   

   2   3     

  / \   \    

 4   5   7

 

At level 1:

1 → NULL

 

At level 2:

2 → 3 → NULL

 

At level 3:

4 → 5 → 7 → NULL

 

Notice that node 6 does not exist, but 5 must still connect directly to 7. This is the important difference from the perfect-tree version.

Example 2

Input

root = []

Output

[]

Explanation

The tree is empty, so there are no nodes whose next pointers need to be populated.

Constraints

0 <= number of nodes <= 6000
-100 <= Node.val <= 100

Hints:

Hint 1

Think about the tree level by level.

Hint 2

For each level, connect every node to the next available node on its right.

Author & Technical Reviewer

ExamAdda Technical Review Team

Technically reviewed by: ExamAdda Technical Review Team

Technical Reviewers, ExamAdda

Software engineers at ExamAdda who check every article's definitions, complexity claims and code examples before and after publishing.

Published

Aug 12, 2026

Last updated

Aug 13, 2026

Content Verification Methodology

Definitions and complexity claims were checked against authoritative computer-science references. Code examples were compiled and tested with standard, boundary and edge-case inputs.

Report a correction:editorial@examadda.org
Auto
Loading editor...
Input

Expected Output