-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path117.populating-next-right-pointers-in-each-node-ii.cpp
More file actions
56 lines (53 loc) · 1.28 KB
/
117.populating-next-right-pointers-in-each-node-ii.cpp
File metadata and controls
56 lines (53 loc) · 1.28 KB
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
/*
* @lc app=leetcode id=117 lang=cpp
*
* [117] Populating Next Right Pointers in Each Node II
*/
// @lc code=start
class Solution {
public:
Node* connect(Node* root) {
Node *parent = root;
Node *cur;
Node *first;
while(parent) {
first = NULL;
while(parent && !(parent->left || parent->right)) parent = parent->next;
if(!parent) break;
if(parent->left) {
cur = parent->left;
first = cur;
if(parent->right) {
cur->next = parent->right;
cur = cur->next;
}
} else {
cur = parent->right;
first = cur;
}
parent = parent->next;
while(cur) {
while(parent && !(parent->left || parent->right)) parent = parent->next;
if(!parent) break;
if(parent->left) {
cur->next = parent->left;
if(parent->right) {
cur = cur->next;
cur->next = parent->right;
}
} else {
cur->next = parent->right;
}
parent = parent->next;
cur = cur->next;
}
parent = first;
}
return root;
}
};
// Accepted
// 55/55 cases passed (18 ms)
// Your runtime beats 54.04 % of cpp submissions
// Your memory usage beats 94.51 % of cpp submissions (17.2 MB)
// @lc code=end