← Home

117. Populating Next Right Pointers in Each Node II

LeetCode article · C++ solution
Website made by wuisabel-gif · Original C++ code by keineahnung2345
two pointersC++Markdown
117

I like to read this solution as a small machine: keep the useful information, throw away the noise. For 117. Populating Next Right Pointers in Each Node II, the solution in this repository is mainly a two pointers solution.

Guide

What?

The first job is to translate the English prompt into state, transition, and stopping conditions. Instead of trying to be clever immediately, read the code as a sequence of questions:

  • What state are we keeping?
  • How do we move from one state to the next?
  • When do we know the answer is already determined?

For this file, the main tools are: two pointers, sliding window.

The notes already sitting in the source point us in the right direction:

  • BFS with queue
  • time: O(N), space: O(N)

Guide

When?

This pattern shows up when the brute force version has too many repeated checks, too many possible branches, or too much bookkeeping to do by hand. The accepted code reduces that pressure by storing exactly the information that remains useful later.

The solution is organized around the main LeetCode entry point and a few local helpers.

Guide

Why?

The code is doing bookkeeping so your brain does not have to keep the entire search space open at once.

  • The queue gives the solution a level-by-level or frontier-style traversal.
  • The final return is not magic; it is the invariant after the loops or recursion have finished doing their accounting.

Guide

How?

Walk through the solution in this order:

  1. Initialize the memory or helper structure.
  2. Process candidates in the order the invariant expects.
  3. Update the answer only when the current state is valid.
  4. Return the value that represents the fully processed input.

The most important competitive-programming habit here is to trust the invariant. Once the invariant is right, the loops become much less scary.

Guide

Complexity

  • Time: O(N), space: O(1)
  • Space: O(n) in the usual case for auxiliary containers or recursion

Guide

C++ Solution

Your submission

The accepted solution

solution.cpp
01//BFS with queue
02//Runtime: 20 ms, faster than 52.71% of C++ online submissions for Populating Next Right Pointers in Each Node II.
03//Memory Usage: 17.9 MB, less than 66.31% of C++ online submissions for Populating Next Right Pointers in Each Node II.
04//time: O(N), space: O(N)
05class Solution {
06public:
07    Node* connect(Node* root) {
08        if(!root) return root;
09        
10        queue<Node*> q;
11        
12        q.push(root);
13        
14        while(!q.empty()){
15            int level_size = q.size();
16            
17            Node* prev = nullptr;
18            
19            while(level_size-- > 0){
20                Node* cur = q.front(); q.pop();
21                
22                if(prev) prev->next = cur;
23                
24                if(cur->left) q.push(cur->left);
25                if(cur->right) q.push(cur->right);
26                
27                prev = cur;
28            }
29        }
30        
31        return root;
32    }
33};
34
35//O(1) space iterative solution
36//https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/37811/Simple-solution-using-constant-space
37//Runtime: 12 ms, faster than 96.85% of C++ online submissions for Populating Next Right Pointers in Each Node II.
38//Memory Usage: 17.7 MB, less than 66.31% of C++ online submissions for Populating Next Right Pointers in Each Node II.
39//time: O(N), space: O(1)
40class Solution {
41public:
42    Node* connect(Node* root) {
43        //first node of next level
44        Node *nhead = nullptr;
45        
46        Node *prev = nullptr, *cur = root;
47        
48        while(cur){
49            //process cur's next level
50            while(cur){
51                if(cur->left){
52                    if(prev){
53                        prev->next = cur->left;
54                    }else{
55                        nhead = cur->left;
56                    }
57                    prev = cur->left;
58                }
59                //else 
60                if(cur->right){
61                    if(prev){
62                        prev->next = cur->right;
63                    }else{
64                        nhead = cur->right;
65                    }
66                    prev = cur->right;
67                }
68                //go to next node in current level
69                cur = cur->next;
70            }
71            
72            //go to next level
73            cur = nhead;
74            prev = nhead = nullptr;
75        }
76        
77        return root;
78    }
79};
80
81//O(1) space(not consider recursion stack) recursive solution
82//https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/172861/Mostly-recursive-solution-O(n)-time-(beats-99.32)-and-O(1)-space-(without-considering-stack)
83//Runtime: 4 ms, faster than 100.00% of C++ online submissions for Populating Next Right Pointers in Each Node II.
84//Memory Usage: 17.6 MB, less than 66.31% of C++ online submissions for Populating Next Right Pointers in Each Node II.
85class Solution {
86public:
87    Node* findnext(Node* node){
88        //recursively find the next leftmost child
89        if(!node) return node;
90        if(node->left) return node->left;
91        if(node->right) return node->right;
92        //current node is leaf, go to its right neighbor
93        return findnext(node->next);
94    }
95    
96    Node* connect(Node* root) {
97        if(!root) return root;
98        
99        if(root->left){
100            Node* target;
101            if(root->right){
102                target = root->right;
103            }else{
104                target = findnext(root->next);
105            }
106            root->left->next = target;
107        }
108        
109        if(root->right){
110            root->right->next = findnext(root->next);
111        }
112        
113        //https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/discuss/172861/Mostly-recursive-solution-O(n)-time-(beats-99.32)-and-O(1)-space-(without-considering-stack)/260137
114        /*
115        in the function "findnext",
116        we will recursively go right,
117        and it requires that the right subtree is connected first,
118        otherwise, therewill be a gap btw left and right subtree
119        
120        consider: [2,1,3,0,7,9,1,2,null,1,0,null,null,8,8,null,null,null,null,7]
121        */
122        connect(root->right);
123        connect(root->left);
124        
125        return root;
126    }
127};

Cost

Complexity

Time
O(N), space: O(1)
Dominated by the main traversal, recursion, or data-structure operations in the code.
Space
O(n) in the usual case for auxiliary containers or recursion
Auxiliary state plus the answer structure where the problem requires one.