Delete Duplicate Folders in System LeetCode solution in JavaScript

1
class Node {
2
constructor(val, parent) {
3
(this.val = val), (this.parent = parent), (this.children = {}), this.hash;
4
}
5
}
6
class Trie {
7
constructor() {
8
this.root = new Node("");
9
this.hashMemo = {};
10
}
11
insert(path) {
12
let cur = this.root;
13
for (let node of path)
14
if (cur.children[node] !== undefined) cur = cur.children[node];
15
else
16
(cur.children[node] = new Node(node, cur)), (cur = cur.children[node]);
17
}
18
traverse(node = this.root) {
19
node.hash = [];
20
if (node.children)
21
for (let child of Object.values(node.children))
22
node.hash.push(this.traverse(child));
23
node.hash = node.hash.join("~");
24
if (node.hash !== "") {
25
if (this.hashMemo[node.hash] === undefined) this.hashMemo[node.hash] = [];
26
this.hashMemo[node.hash].push(node);
27
return node.val + "/[" + node.hash + "]";
28
}
29
return node.val;
30
}
31
delete(node = this.root) {
32
if (!node || node.hash === undefined) return;
33
else if (this.hashMemo[node.hash] && this.hashMemo[node.hash].length > 1)
34
for (let todelete of this.hashMemo[node.hash])
35
delete todelete.parent.children[todelete.val];
36
else for (let child of Object.values(node.children)) this.delete(child);
37
}
38
serialize(node = this.root, stack = [], res = []) {
39
if (node.val !== "") stack.push(node.val), res.push([...stack]);
40
for (let child of Object.values(node.children))
41
this.serialize(child, stack, res);
42
stack.pop();
43
return res;
44
}
45
}
46

47
var deleteDuplicateFolder = function (paths) {
48
let T = new Trie();
49
for (let P of paths) T.insert(P);
50
T.traverse();
51
T.delete();
52
return T.serialize();
53
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0