创建递归二叉树?
我有两个堆栈,一个带有操作数,另一个带有运算符。我的问题是将这两个堆栈变成二叉树。
例如,表达式(2+3)*(4-3)
将被翻译为后缀(例如 24+43-*
),然后放入两个堆栈 3442
和 *-+
将是堆栈(顶部分别为 3 和 *)。
现在有了这些堆栈,我需要形成一个二叉树,例如
*
+ -
2 3 4 3
有没有办法递归地执行此操作?
现在,我有一个像这样的算法:
创建树的根,将根的值分配给运算符堆栈中的第一个运算符。将左右指针设置为空。
创建右侧节点,如果存在则分配下一个运算符的值,如果不存在则为其分配操作数。然后对左节点执行相同的操作。
我的问题是使其递归,或者让它处理许多不同的情况。
感谢您的帮助。
I have two stacks, one with operands, the other with operators. My problem is turning these two stacks into a binary tree.
For example, the expression (2+3)*(4-3)
will be translated into postfix ( such that 24+43-*
) and then put into two stacks3442
and *-+
will be the stacks (with the tops being 3 and * respectively).
Now with these stacks, i need to form a binary tree like
*
+ -
2 3 4 3
Is there a way to do this recursively?
Right now, I have an algorithm like so:
Create the root of the tree, assign the value of the root to the first operator in the operator-stack. Set the right and left pointers to null.
Create the right node, assign the value of the next operator if it exists, if not assign it an operand. Then do the same for the left node.
My problem is making this recursive, or getting it to handle the many different cases.
Thanks for your help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
假设你只有二元运算符
assuming you have only binary operators
递归算法:
Recursive algorithm:
如果您的表达式始终是对称的(运算符每一侧的操作数和运算符数量相同),那么您描述的方法可以正常工作,只需稍作修改:
(Jan 在他的回答中解释得更清楚......)
if your expression is always symmetrical (the same number of operands and operators on each side of an operator), then the method you describe works fine, with a little modification:
(Jan explained it so much clearer in his answer...)
一般来说,没有办法做到这一点。 “1 2 3 4”“* + /”是指“1 2 3 4 * + /”(即“1 / (2 + 3 * 4)”)还是“1 2 * 3 + 4 /”,(即“(1 * 2 + 3) / 4”)。
In general there isn't a way of doing this. Does "1 2 3 4" "* + /" mean "1 2 3 4 * + /" (that is, "1 / (2 + 3 * 4)") or "1 2 * 3 + 4 /" , (that is "(1 * 2 + 3) / 4").