我有两个堆栈,一个有操作数,另一个有运算符。我的问题是把这两个堆栈变成二叉树。
例如,表达式(2+3)*(4-3)
将被翻译为后缀(例如24+43-*
),然后放入两个堆栈中-- 3442
和*-+
将是堆栈(顶部分别为3和*)。
现在使用这些堆栈,我需要形成一棵二叉树,如
*
+ -
2 3 4 3
有什么方法可以递归地这样做吗?
现在,我有一个这样的算法:
我的问题是使这个递归,或让它来处理许多不同的情况。
谢谢你的帮助。
发布于 2010-11-11 15:35:18
假设您只有二进制运算符
treeNode createNode(operators, operands) {
// take first operator and create a new treeNode with it. pop it from the operators stack
// if it is the last operator in the list then there should be only two operands left in the operands and you can assign them to the left and right child of the treeNode. return this treeNode.
// if it is not the last operator then split the operands in two stacks equally
// leftOperands and rightOperands
// left child becomes createNode(operators, leftoperands)
// right child becomes createNode(operators, rightoperands)
// return this treeNode
}
发布于 2010-11-11 15:26:05
递归算法:
operator
上。
发布于 2010-11-11 15:39:00
如果您的表达式总是对称的(操作符两边的操作数和操作符的数目相同),那么您描述的方法工作得很好,只需稍作修改:
(简在回答中解释得很清楚.)
https://stackoverflow.com/questions/4155975
复制相似问题