-
Notifications
You must be signed in to change notification settings - Fork 0
/
Problem-117.cpp
89 lines (84 loc) · 2.41 KB
/
Problem-117.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Problem - 117
// https://leetcode.com/problems/populating-next-right-pointers-in-each-node-ii/
// O(n) time complexity and O(n) space complexity solution using dfs
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return root;
if(root->left) {
if(root->right) {
root->left->next = root->right;
}
else {
Node* curr = root->next;
while(curr) {
if(curr->left) {
root->left->next = curr->left;
break;
}
if(curr->right) {
root->left->next = curr->right;
break;
}
curr = curr->next;
}
}
}
if(root->right) {
Node* curr = root->next;
while(curr) {
cout << curr->val << " ";
if(curr->left) {
root->right->next = curr->left;
break;
}
if(curr->right) {
root->right->next = curr->right;
break;
}
curr = curr->next;
}
cout <<endl;
}
connect(root->right);
connect(root->left);
return root;
}
};
// OR O(n) time complexity and O(1) space complexity solution
class Solution {
public:
Node* connect(Node* root) {
if(!root)
return root;
Node* curr = root, *nextLevelHead = NULL, *prev = NULL;
while(curr) {
while(curr) {
if(curr->left) {
if(!prev) {
nextLevelHead = curr->left;
}
else {
prev->next = curr->left;
}
prev = curr->left;
}
if(curr->right) {
if(!prev) {
nextLevelHead = curr->right;
}
else {
prev->next = curr->right;
}
prev = curr->right;
}
curr = curr->next;
}
curr = nextLevelHead;
nextLevelHead = NULL;
prev = NULL;
}
return root;
}
};