eval(left, right) { // 计算节点值 switch (this.data) { case'+': return left + right case'-': return left - right case'*': return left * right case'/': return left / right default: throw'Error Operator: ' + this.data } } }
/** * 解析表达式 * @param {String} exp 表达式 */ parse_exp() { for (let i ofthis.exp) { if (i.trim() === '') { continue } else { if (!this.op.includes(i)) { // 数值压入数据栈中 this.data_stack.push(parseInt(i)) } elseif (this.op_stack.top() === null || i === '(') { // 栈顶为空或者是开括号 this.op_stack.push(i) } elseif (i === ')') { // 符号为闭括号, 循环弹出符号并添加到节点 let top = this.op_stack.pop() while (top != '(') { this.setNode(top) top = this.op_stack.pop() } } elseif (priority[this.op_stack.top()] >= priority[i]) { // 判断优先级,添加到节点 let top = this.op_stack.pop() this.setNode(top) this.op_stack.push(i) } else { this.op_stack.push(i) } } }
// 生成表达式树 let top = this.op_stack.pop() while (top) { this.setNode(top) top = this.op_stack.pop() } this.root = this.data_stack.pop() }
setNode(op) { // 表达式转换成节点 let right = this.data_stack.pop() let left = this.data_stack.pop() let node = new Node(op, left, right) this.data_stack.push(node) } }
let et = new ExpTree('(1 + 2) * (5 - 3)') et.parse_exp() console.log(et.root)