deno.land / x / masx200_leetcode_test@10.6.5 / recover-a-tree-from-preorder-traversal / 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
import { TreeNode } from "../binary-tree-inorder-traversal/TreeNode.ts";
export default function recoverFromPreorder( traversal: string,): TreeNode | null { const depth_to_tree = new Map<number, TreeNode>(); for (const [depth, value] of parse(traversal)) { const tree = new TreeNode(value); if (depth > 0) { const parent = depth_to_tree.get(depth - 1); if (parent) { if (parent.left) parent.right = tree; else { parent.left = tree; } } } depth_to_tree.set(depth, tree); } return depth_to_tree.get(0) ?? null;}function* parse(s: string): Generator<[number, number]> { let depth = 0; let value = 0; const len = s.length; for (let i = 0; i < len; i++) { if (s[i] === "-") { depth++; continue; } while (i < len && /\d/.test(s[i])) { value = value * 10 + Number(s[i]); i++; } i--; yield [depth, value]; depth = 0; value = 0; }}
masx200_leetcode_test
leetcode题解和一些测试工具
DocumentationDocumentation
GitHub Repositorymasx200/leetcode-test
GitHub Stars
4

Version Info

Tagged at
4 months ago