-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathProblem-116.cpp
42 lines (37 loc) · 1.01 KB
/
Problem-116.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Problem - 116
// https://leetcode.com/problems/populating-next-right-pointers-in-each-node/
// O(n) time complexity and O(n) space complexity solution using recursion
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return NULL;
if(root->left) {
root->left->next = root->right;
if(root->next)
root->right->next = root->next->left;
}
connect(root->left);
connect(root->right);
return root;
}
};
// OR O(n) time complexity and O(1) space complexity solution
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return NULL;
Node* curr, *pre = root;
while(pre->left) {
curr = pre;
while(curr) {
curr->left->next = curr->right;
if(curr->next) curr->right->next = curr->next->left;
curr = curr->next;
}
pre = pre->left;
}
return root;
}
};