Generate syntax tree for simple math operations

后端 未结 4 1462
故里飘歌
故里飘歌 2020-12-31 19:27

I am trying to generate a syntax tree, for a given string with simple math operators (+, -, *, /, and parenthesis). Given the string \"1 + 2 * 3\":

It shou

4条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-31 19:58

    I built a fun little calculator once and had the same problem as you, which I solved by building the syntax tree without keeping the order precedence in mind,firstly. Each node has a precedence value, and when eval'ing non-constants, I'd check the left node: if it has lower precedence, I'd rotate the tree clockwise: bring it into evaluation and evaluate that first, likewise for the right node. then I'd just try to evaluate again. It seemed to work well enough for me.

提交回复
热议问题