deno.land / x / masx200_leetcode_test@10.6.5 / design-an-expression-tree-with-evaluate-function / 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
export { TreeBuilder as default };class TreeBuilder { buildTree(postfix: string[]): Node { const stack: Node[] = [];
for (const char of postfix) { if (isNumber(char)) { stack.push(new Node(char)); } else { const num2 = stack.pop(); const num1 = stack.pop(); if (typeof num2 == "undefined") { throw Error("number expected"); } if (typeof num1 == "undefined") { throw Error("number expected"); } if (char === "+") { stack.push(new Node(char, num1, num2)); } else if (char === "-") { stack.push(new Node(char, num1, num2)); } else if (char === "*") { stack.push(new Node(char, num1, num2)); } else if (char === "/") { stack.push(new Node(char, num1, num2)); } else throw Error("unknown operator:" + char); } } return stack[0]; }}export class Node { constructor( public val: string = "", public left: Node | null = null, public right: Node | null = null, ) {} evaluate(): number { if (this.left == null && this.right == null) return Number(this.val); if (!(this.left && this.right)) { throw Error("accident"); } const l = this.left.evaluate(); const r = this.right.evaluate();
switch (this.val) { case "+": return l + r; case "-": return l - r; case "*": return l * r; case "/": return Math.trunc(l / r); } throw Error("unknown operator:" + this.val); }}export function isNumber(token: string) { return /\d+/g.test(token);}
masx200_leetcode_test

Version Info

Tagged at
a year ago