Skip to content

Commit 8b4ad2a

Browse files
authored
Create 430-flatten-a-multilevel-doubly-linked-list.js
1 parent 2f0d6ce commit 8b4ad2a

File tree

1 file changed

+31
-0
lines changed

1 file changed

+31
-0
lines changed
Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
/**
2+
* // Definition for a Node.
3+
* function Node(val,prev,next,child) {
4+
* this.val = val;
5+
* this.prev = prev;
6+
* this.next = next;
7+
* this.child = child;
8+
* };
9+
*/
10+
/**
11+
* @param {Node} head
12+
* @return {Node}
13+
*/
14+
const flatten = function (head) {
15+
const handle = (node, next = null) => {
16+
if (!node) return null;
17+
handle(node.next, next);
18+
const child = handle(node.child, node.next);
19+
if (!node.next && next) {
20+
node.next = next;
21+
next.prev = node;
22+
}
23+
if (child) {
24+
node.next = child;
25+
node.child = null;
26+
child.prev = node;
27+
}
28+
return node;
29+
};
30+
return handle(head);
31+
};

0 commit comments

Comments
 (0)