Skip to content

Commit 048c007

Browse files
authored
Create 1597-build-binary-expression-tree-from-infix-expression.js
1 parent 94cd74b commit 048c007

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
/**
2+
* Definition for a binary tree node.
3+
* function Node(val, left, right) {
4+
* this.val = (val===undefined ? " " : val)
5+
* this.left = (left===undefined ? null : left)
6+
* this.right = (right===undefined ? null : right)
7+
* }
8+
*/
9+
/**
10+
* @param {string} s
11+
* @return {Node}
12+
*/
13+
const expTree = function(s) {
14+
const list = s.split('')
15+
const mdSet = new Set(['*', '/'])
16+
const amSet = new Set(['+', '-'])
17+
return parseExpression(list)
18+
19+
function parseExpression(tokens) {
20+
let lhs = parseTerm(tokens)
21+
while(tokens.length && amSet.has(tokens[0])) {
22+
const op = tokens.shift()
23+
const rhs = parseTerm(tokens)
24+
lhs = new Node(op, lhs, rhs)
25+
}
26+
return lhs
27+
}
28+
function parseTerm(tokens) {
29+
let lhs = parseFactor(tokens)
30+
while(tokens.length && mdSet.has(tokens[0])) {
31+
const op = tokens.shift()
32+
const rhs = parseFactor(tokens)
33+
lhs = new Node(op, lhs, rhs)
34+
}
35+
return lhs
36+
}
37+
function parseFactor(tokens) {
38+
if(tokens[0] === '(') {
39+
tokens.shift()
40+
const node = parseExpression(tokens)
41+
tokens.shift()
42+
return node
43+
} else {
44+
const token = tokens.shift()
45+
return new Node(token)
46+
}
47+
}
48+
};

0 commit comments

Comments
 (0)