递归-二叉树生成表达式
// 数据
// 数据处理:
// left和right填写的子节点的位置,子节点需要添加partent
let listNode = [
{id:'1',partent:'',left:'2',right:'3',value:'+'},
{id:'2',partent:'1',left:'',right:'',value:'1'},
{id:'3',partent:'1',left:'',right:'',value:'2'},
]
let root = listNode.filter(i => i.parent === '')
// 调用
let expression = buildExpression(root.id, listNode)
// 方法
buildExpression(id,arr) {
let node = arr.find(obj => obj.id === id);
if (!node) return '';
let leftExpr = buildExpression(node.left,arr);
let rightExpr = buildExpression(node.right,arr);
if (node.type === 'compare') {
return '(' + leftExpr + ' ' + node.value + ' ' + rightExpr + ')';
} else {
return node.value;
}
}
栈-数组生成表达式
// 将list数组按顺序依次相加形成表达式
let list = [{ value: '111', relation: '' }, { value: '222', relation: '/' }, { value: '333', relation: '+' }, { value: '22', relation: '+' }, { value: '43', relation: '/' }]
let stack = []
list.forEach(item => {
if (item.value !== '') {
if (item.relation === '') {
stack.push(item.value)
} else {
stack.push(item.relation)
stack.push(item.value)
}
}
})
while (stack.length > 1) {
let operand2 = stack.pop()
let operator = stack.pop()
let operand1 = stack.pop()
stack.push(`${operand1}${operator}${operand2}`)
}
let expression = stack[0]
console.log(expression)
// 111/222+333+22/43