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 II Constant Space Solution INPUT Binary Tree Structure 1 2 3 4 5 6 7 root = [1,2,3,4,5,6,7] All next pointers = NULL (initially) ALGORITHM STEPS 1 Use dummy node Track next level start 2 Process current level Using existing next ptrs 3 Connect children Build next level links 4 Move to next level Repeat until done Level Traversal 2 3 NULL Red dashed = next pointer Time: O(n) | Space: O(1) No queue needed! FINAL RESULT Tree with Next Pointers 1 NULL 2 3 4 5 6 7 [1,2,3,4,5,6,7] Legend = next pointer OK - All nodes connected! Key Insight: Use a dummy node to track the first node of the next level. While traversing the current level using existing next pointers, connect all children of current level nodes. This eliminates the need for a queue, achieving O(1) space complexity. Works for any binary tree structure! TutorialsPoint - Populating Next Right Pointers in Each Node II | Constant Space Solution
Asked in
Microsoft 15 Amazon 12 Facebook 8 Google 6
89.6K 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