从代数表达式创建二叉树
我必须用 Java 创建一个算术计算器。为此,我必须解析二叉树中的代数表达式,然后计算并返回结果。那么第一步如何解析二叉树中的表达式?我知道这个理论,但我的问题是如何在 Java 中做到这一点。我读了下面的帖子 创建递归二叉树
但是我缺少基本的技巧或方法。我知道如何创建一个节点(我有一个类,其中包含 returnNodeValue、isLeaf、isDoubleNode、isSingleNode 等方法),但我认为我需要一个方法来在二叉树中插入节点来实现我想要的。有什么想法吗?
I have to create an arithmetic evaluator in Java. To do this I have to parse an algebric expression in binary tree and then calculate and return the result. So for the first step how can I parse an expression in a binary tree? I know the theory but my prob is how to do it in Java. I read the following post
create recursive binary tree
But I'm missing the basic trick or method. I know how to create a node (I have a class with methods like returnNodeValue, isLeaf, isDoubleNode, isSingleNode etc) but I think I'll need a method to insert a node in a binary tree to acheive what I want. Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
前缀表达式的树结构
让我们做一个例子:
+ 2 + 1 1
Apply (0)。
应用(1)。
应用(2)。
应用(1)。
最后,应用(2)。
该算法已针对
- * / 15 - 7 + 1 1 3 + 2 + 1 1
进行了测试,因此
Tree.insert
实现就是这三个规则。评估树有点有趣,因为你必须从树的右下角开始。执行反向后序遍历。首先拜访正确的孩子。
鉴于从前缀表达式构造树的简单性,我建议使用标准的堆栈算法从中缀转换为前缀。在实践中,您可以使用堆栈算法来计算中缀表达式。
Tree construction for prefix expressions
Let's do an example:
+ 2 + 1 1
Apply (0).
Apply (1).
Apply (2).
Apply (1).
Finally, apply (2).
This algorithm has been tested against
- * / 15 - 7 + 1 1 3 + 2 + 1 1
So the
Tree.insert
implementation is those three rules.Evaluating the tree is a little funny, because you have to start from the bottom-right of the tree. Perform a reverse post-order traversal. Visit the right child first.
Given the simplicity of constructing a tree from a prefix expression, I'd suggest using the standard stack algorithm to convert from infix to prefix. In practice you'd use a stack algorithm to evaluate an infix expression.
我认为您可能对自己应该做什么感到有点困惑:
您所说的二叉树实际上是一个解析树,并且它不是严格意义上的二叉树(因为并非所有树节点是二进制的)。 (除了“二叉树”具有二叉搜索树的含义,而这根本不是您在这里需要的。)
您已经弄清楚如何解析表达式,解析树的构造非常漂亮直截了当。例如:
注意:这不是工作代码...这是帮助您做作业的提示。
I think you might be a bit confused about what you are supposed to be doing:
The binary tree you are talking about is actually a parse tree, and it is not strictly a binary tree (since not all tree nodes are binary). (Besides "binary tree" has connotations of a binary search tree, and that's not what you need here at all.)
One you have figured out to parse the expression, the construction of the parse tree is pretty straight-forward. For instance:
Note: this is not working code ... it is a hint to help you do your homework.