-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProblem_0430_flatten.cc
More file actions
59 lines (54 loc) · 986 Bytes
/
Copy pathProblem_0430_flatten.cc
File metadata and controls
59 lines (54 loc) · 986 Bytes
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
#include <iostream>
#include <vector>
#include "UnitTest.h"
using namespace std;
class Node
{
public:
int val;
Node *prev;
Node *next;
Node *child;
};
class Solution
{
public:
Node *dfs(Node *node)
{
Node *cur = node;
Node *last = nullptr;
while (cur)
{
Node *next = cur->next;
if (cur->child)
{
// 优先处理子节点
Node *child_last = dfs(cur->child);
// cur 与 child 相连
cur->next = cur->child;
cur->child->prev = cur;
if (next)
{
// 如果有 next,将 child_last 与 next 相连
child_last->next = next;
next->prev = child_last;
}
// 清空 child 指针
cur->child = nullptr;
// 记录最后一个节点
last = child_last;
}
else
{
last = cur;
}
cur = next;
}
return last;
}
Node *flatten(Node *head)
{
dfs(head);
return head;
}
};