deno.land / x / masx200_leetcode_test@10.6.5 / serialize-and-deserialize-n-ary-tree / index.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
68
69
70
71
72
73
74
75
76
import { Node } from "../n-ary-tree-level-order-traversal/Node.ts";
export function serialize(root: Node | null): string { return JSON.stringify(NAryNodeToArray(root)).replaceAll("null", "");}export function deserialize(data: string): Node | null { return ArrayToNAryNode( JSON.parse(data.replaceAll(",,", ",null,").replaceAll("[,", "[null,")), );}function NAryNodeToArray(root: Node | null): (number[] | null)[][] { if (!root) return []; let current: Node[] = [root]; const result: (number[] | null)[][] = [[[root.val]]]; while (current.length > 0) { const next: Node[] = []; const temp: (number[] | null)[] = []; for (const node of current) { const values: number[] = []; for (const child of node.children) { next.push(child); values.push(child.val); } if (values.length) { temp.push(values); } else { temp.push(null); } } while (temp.length > 1) { if (!temp[temp.length - 1]) { //删除末尾的null temp.length--; } else { break; } } result.push(temp); current = next; } if (result.length > 1) { // console.log(result.at(-1)); //最后一个全为空删掉 result.length--; } return result;}function ArrayToNAryNode(array: (number[] | null)[][]): Node | null { if (array.length === 0) { return null; } const first = array[0]?.[0]?.[0]; if (typeof first === "undefined") { return null; } const root = new Node(first); let current = [root]; for (let i = 1; i < array.length; i++) { const next: Node[] = []; const temp = array[i]; for (const [j, values] of temp.entries()) { if (values) { // console.log(values); values .map((v) => new Node(v)) .forEach(function (n) { current[j].children.push(n); next.push(n); }); } } current = next; } return root;}
masx200_leetcode_test

Version Info

Tagged at
a year ago