-
-
Notifications
You must be signed in to change notification settings - Fork 298
/
Copy path430.cpp
98 lines (92 loc) · 2.11 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
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
90
91
92
93
94
95
96
97
98
__________________________________________________________________________________________________
sample 96 ms submission
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node() {}
Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/
class Solution {
public:
Node* flatten(Node* head) {
stack <Node *> st;
Node *cur = head, *prev = nullptr;
while (!st.empty() || cur) {
if (cur == nullptr) {
cur = st.top(); st.pop();
prev->next = cur;
prev->next->prev = prev;
}
if (cur->child != nullptr) {
if (cur->next) st.push(cur->next);
cur->next = cur->child;
cur->next->prev = cur;
cur->child = nullptr;
}
prev = cur;
cur = cur->next;
}
return head;
}
};
static int fastio = []() {
#define endl '\n'
std::ios::sync_with_stdio(false);
std::cin.tie(NULL);
std::cout.tie(0);
return 0;
}();
__________________________________________________________________________________________________
sample 29808 kb submission
/*
// Definition for a Node.
class Node {
public:
int val;
Node* prev;
Node* next;
Node* child;
Node() {}
Node(int _val, Node* _prev, Node* _next, Node* _child) {
val = _val;
prev = _prev;
next = _next;
child = _child;
}
};
*/
class Solution {
void dfs(Node* ptr, Node* &pre){
if (!ptr) return;
if (pre) pre->next=ptr;
ptr->prev=pre;
pre=ptr;
auto* next=ptr->next;
if (ptr->child){
auto* nextLevel=ptr->child;
ptr->child=NULL;
while (nextLevel->prev)
nextLevel=nextLevel->prev;
dfs(nextLevel, pre);
}
dfs(next, pre);
}
public:
Node* flatten(Node* head) {
Node* pre=NULL;
dfs(head, pre);
return head;
}
};
__________________________________________________________________________________________________