-
Notifications
You must be signed in to change notification settings - Fork 3
/
solution.ts
67 lines (53 loc) · 1.15 KB
/
solution.ts
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
/*
* @lc app=leetcode id=430 lang=javascript
*
* [430] Flatten a Multilevel Doubly Linked List
*/
// @lc code=start
/**
* // Definition for a Node.
* function Node(val,prev,next,child) {
* this.val = val;
* this.prev = prev;
* this.next = next;
* this.child = child;
* };
*/
type MaybeNode = Node | null;
interface Node {
val: number;
prev: MaybeNode;
next: MaybeNode;
child: MaybeNode;
}
/**
* @param {Node} head
* @return {Node}
*/
const flatten = (head: MaybeNode): MaybeNode => {
// * ['52 ms', '89.91 %', '34.1 MB', '100 %']
if (head === null) return head;
flattenReturnEnd(head);
return head;
};
const flattenReturnEnd = (head: Node): Node => {
let cur = { next: head } as Node;
while (cur.next || cur.child) {
if (cur.child) {
const next = cur.next;
const child = cur.child;
const childEnd = flattenReturnEnd(cur.child);
cur.child = null;
cur.next = child;
child.prev = cur;
childEnd.next = next;
if (next !== null) next.prev = childEnd;
cur = childEnd;
} else {
cur = cur.next!;
}
}
return cur;
};
// @lc code=end
export { flatten };