-
Notifications
You must be signed in to change notification settings - Fork 42
/
Copy pathProblem50.js
47 lines (43 loc) · 1.11 KB
/
Problem50.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
// Problem 50
//
// This problem was asked by Microsoft.
//
// Suppose an arithmetic expression is given as a binary tree.
// Each leaf is an integer and each internal node is one of '+', '−', '∗', or '/'.
//
// Given the root to such a tree, write a function to evaluate it.
//
// For example, given the following tree:
//
// *
// / \
// + +
// / \ / \
// 3 2 4 5
// You should return 45, as it is (3 + 2) * (4 + 5).
//
// O(N) Time complexity
// O(H) Space complexity
// N is the number of nodes, and H is the height of the tree
import isNumber from 'is-number';
/**
* Evaluates the expression tree, given root. Postorder traversal
* @param {TreeNode} tree
* @return {number}
*/
function evalExpressionTree(tree) {
if (isNumber(tree.val)) return tree.val;
const valLeft = evalExpressionTree(tree.left);
const valRight = evalExpressionTree(tree.right);
switch (tree.val) {
case '+':
return valLeft + valRight;
case '-':
return valLeft - valRight;
case '*':
return valLeft * valRight;
default:
return valLeft / valRight;
}
}
export default evalExpressionTree;