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
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
💡
Explanation
AI Ready
💡 Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code