Populating Next Right Pointers in Each Node II - Problem

Given a binary tree with the following structure:

struct Node {
    int val;
    Node *left;
    Node *right;
    Node *next;
}

Populate each next pointer to point to its next right node. If there is no next right node, the next pointer should be set to NULL.

Initially, all next pointers are set to NULL.

Note: This is the general case where the binary tree can be any binary tree (not necessarily a perfect binary tree).

Input & Output

Example 1 — Perfect Binary Tree
$ Input: root = [1,2,3,4,5,6,7]
Output: [1,2,3,4,5,6,7]
💡 Note: Level 0: 1; Level 1: 2 → 3; Level 2: 4 → 5 → 6 → 7. Each node points to its next right node in the same level.
Example 2 — General Binary Tree
$ Input: root = [1,2,3,4,5,null,7]
Output: [1,2,3,4,5,7]
💡 Note: Level 0: 1; Level 1: 2 → 3; Level 2: 4 → 5 → 7. Node 6 is missing, so 5 connects directly to 7.
Example 3 — Single Node
$ Input: root = [1]
Output: [1]
💡 Note: Only one node exists, so no next pointers need to be set.

Constraints

  • The number of nodes in the tree is in the range [0, 6000]
  • -100 ≤ Node.val ≤ 100

Visualization

Tap to expand
Populating Next Right Pointers in Each Node IIBEFORE: No Connections123457AFTER: All Connected123457Input: [1,2,3,4,5,null,7]Level 1: 2 → 3Level 2: 4 → 5 → 7Each node now points to its next right node!Orange arrows show the next pointers we need to establish
Understanding the Visualization
1
Input
Binary tree [1,2,3,4,5,null,7] with null next pointers
2
Process
Connect nodes level by level: 2→3, then 4→5→7
3
Output
Same tree with all next pointers populated
Key Takeaway
🎯 Key Insight: Connect nodes level by level using the tree's natural structure - either with BFS or by leveraging already established connections
Asked in
Microsoft 15 Amazon 12 Facebook 8 Google 6
89.5K Views
Medium Frequency
~25 min Avg. Time
2.3K Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen