-
Notifications
You must be signed in to change notification settings - Fork 115
/
0430-FlattenAMultilevelDoublyLinkedList.cs
69 lines (61 loc) · 1.7 KB
/
0430-FlattenAMultilevelDoublyLinkedList.cs
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
//-----------------------------------------------------------------------------
// Runtime: 88ms
// Memory Usage: 24.6 MB
// Link: https://leetcode.com/submissions/detail/365288872/
//-----------------------------------------------------------------------------
namespace LeetCode
{
/*
// Definition for a Node.
public class Node {
public int val;
public Node prev;
public Node next;
public Node child;
}
*/
public class _0430_FlattenAMultilevelDoublyLinkedList
{
public Node Flatten(Node head)
{
var dummy = new Node();
dummy.next = head;
var curr = dummy;
FlattenHelper(curr);
return dummy.next;
}
private Node FlattenHelper(Node head)
{
var curr = head;
while (curr != null)
{
if (curr.child == null)
{
if (curr.next != null)
{
curr = curr.next;
continue;
}
else
break;
}
var next = curr.next;
var nextLevelTail = FlattenHelper(curr.child);
curr.next = curr.child;
curr.child.prev = curr;
curr.child = null;
nextLevelTail.next = next;
if (next != null)
next.prev = nextLevelTail;
}
return curr;
}
public class Node
{
public int val;
public Node prev;
public Node next;
public Node child;
}
}
}