-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsolution.js
52 lines (46 loc) · 1.34 KB
/
solution.js
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
class TreeNode {
/**
*
* @param {TreeNode} left
* @param {TreeNode} right
* @param {*} val
*/
constructor(left, right, val) {
this.left = left;
this.right = right;
this.val = val;
}
isLeaf() {
return !this.left && !this.right;
}
}
/**
*
* @param {TreeNode} treeNode
*/
function calculate(treeNode) {
if (treeNode.isLeaf()) return treeNode.val;
switch (treeNode.val) {
case "*":
treeNode.val = calculate(treeNode.left) * calculate(treeNode.right);
break;
case "+":
treeNode.val = calculate(treeNode.left) + calculate(treeNode.right);
break;
case "-":
treeNode.val = calculate(treeNode.left) - calculate(treeNode.right);
break;
case "/":
treeNode.val = calculate(treeNode.left) / calculate(treeNode.right);
break;
}
return treeNode.val;
}
const testTree1 = new TreeNode(null, null, 3);
const testTree2 = new TreeNode(null, null, 2);
const testTree3 = new TreeNode(null, null, 4);
const testTree4 = new TreeNode(null, null, 5);
const testTree5 = new TreeNode(testTree1, testTree2, "+");
const testTree6 = new TreeNode(testTree3, testTree4, "+");
const testTree7 = new TreeNode(testTree5, testTree6, "*");
console.log(calculate(testTree7)); // 45