-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy path430.cpp
42 lines (41 loc) · 1.07 KB
/
430.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
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
};
*/
class Solution {
public:
vector<Node*> recursive(Node* node) {
Node* prev = nullptr;
Node* curr = node;
if (curr == nullptr) return {node, node};
Node* next = node->next;
while (curr) {
if (curr->child != nullptr) {
vector<Node*> middle = recursive(curr->child);
Node* middleStart = middle[0];
Node* middleEnd = middle[1];
curr->next = middleStart;
middleStart->prev = curr;
middleEnd->next = next;
curr->child = nullptr;
if (next == nullptr) {
return {node, middleEnd};
}
else next->prev = middleEnd;
}
prev = curr;
curr = next;
if (next != nullptr) next = next->next;
}
return {node, prev};
}
Node* flatten(Node* head) {
return recursive(head)[0];
}
};