-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBinaryExpressionTree.js
More file actions
62 lines (55 loc) · 1.59 KB
/
BinaryExpressionTree.js
File metadata and controls
62 lines (55 loc) · 1.59 KB
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
class Node {
constructor(data) {
this.data = data,
this.left = null,
this.right = null
}
}
class BinaryExpressionTree {
constructor() {
this.stack = [],
this.operations = {
'^': (a, b) => a ** b,
'*': (a, b) => a * b,
'/': (a, b) => a / b,
'+': (a, b) => a + b,
'-': (a, b) => a - b
}
}
parse(expression) {
expression.forEach((char) => {
const node = new Node(char)
if (!Object.keys(this.operations).includes(char)) {
node.data = parseInt(node.data, 10)
this.stack.push(node)
} else {
node.right = this.stack.pop()
node.left = this.stack.pop()
this.stack.push(node)
}
})
}
operate(n1, o, n2) { // operand in middle
return this.operations[o](n1, n2)
}
evaluate(root) {
if (!root.data) {
return 0
}
if (!root.left && !root.right) {
return root.data
}
const leftResult = this.evaluate(root.left)
const rightResult = this.evaluate(root.right)
return this.operate(leftResult, root.data, rightResult)
}
returnAnswer() {
return this.evaluate(this.stack[0])
}
}
const input = ['8', '2', '^', '6', '+', '2', '10', '*', '2', '/', '-']
const testTree = new BinaryExpressionTree()
testTree.parse(input)
const answer = testTree.returnAnswer()
console.log('postfix input: ', input.join(' '))
console.log('answer: ', answer)