Converting an infix expression (with parentheses) into a binary tree

给你一囗甜甜゛ 提交于 2020-01-02 03:17:06

问题


As part of a Java assignment, I have to take an input arithmetic expression and store it in a binary tree.

I have done everything necessary for the assignment except for the part where I read in the string of the expression and store it in the binary tree.

I have created a class called BinaryTree. Its only field is a treenode called root. This treenode is defined as an innerclass in BinaryTree. It has 3 fields, a generic data field, and two children (left and right) that are type BinaryTree.

I'm having a very difficult time defining an algorithm for reading in an expression such as

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

and storing it in a tree like this

             /
        ^          2
    *       3
  5   +
     2  3

Can anyone help with the algorithm?


回答1:


Take a look at the shunting-yard algorithm. From Wikipedia:

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.




回答2:


Here is some C++ code to create a binary expression tree that uses two stacks, one for the operators and another for the operands. Eventually, the operand stack contains one element, the complete binary expression tree.



来源:https://stackoverflow.com/questions/10303506/converting-an-infix-expression-with-parentheses-into-a-binary-tree

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!