java - 将中缀表达式(带括号)转换为二叉树

标签 java math tree expression binary-tree

作为 Java 赋值的一部分,我必须采用输入算术表达式并将其存储在二叉树中。

除了我读入表达式的字符串并将其存储在二叉树中的部分外,我已经完成了赋值所需的一切。

我创建了一个名为 BinaryTree 的类。它唯一的字段是一个名为 root 的树节点。此树节点在二叉树中定义为内部类。它有 3 个字段、一个通用数据字段和两个 BinaryTree 类型的子项(左和右)。

我很难定义用于读取表达式的算法,例如

(5*(2+3)^3)/2

并像这样将其存储在树中

             /
        ^          2
    *       3
  5   +
     2  3

任何人都可以帮助算法吗?

最佳答案

看看 shunting-yard algorithm .来自维基百科:

In computer science, the shunting-yard algorithm is a method for parsing mathematical expressions specified in infix notation. It can be used to produce output in Reverse Polish notation (RPN) or as an abstract syntax tree (AST). The algorithm was invented by Edsger Dijkstra and named the "shunting yard" algorithm because its operation resembles that of a railroad shunting yard. Dijkstra first described the Shunting Yard Algorithm in Mathematisch Centrum report MR 34/61.

关于java - 将中缀表达式(带括号)转换为二叉树,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10303506/

相关文章:

tree - 检查节点是否属于 tree lisp

java - 使用 Joox 解析 Xml 字符串

java - 如何使异步任务在 Java 8 中具有较低的优先级?

数学和游戏编程

ruby - 如何在 Ruby 中将数字数组转换为矩阵

java - ZK内部类树属性不可读

java - Hibernate可以将空字符串默认为空字符串吗

java - Java中如何获取Instrumentation实例

java - 分布式 "dumping"/"compressing"数据样本

javascript - 如何追踪树状数据结构的所有路径?