Building expression tree

核能气质少年 提交于 2019-12-11 13:25:25

问题


Given a expression like 4 * 5 + 9, how can we build a expression tree out of this?
I was reading this interview question on job portal and thought of trying it.

The problem is if this had been parenthesized, it would had been little easier to build

For example ((4 * 5) + 9).
Then with the opening of left parenthesis, we would know we have to go left, wherein the number would be a leaf node and operator would be parent, and once we hit right parenthesis, we would return and go up the level.

How can we build such expression trees?


回答1:


you can start with BNF and work your way to the tree. in case of simple expressions with parenthesis that would be

 EXPR ::= TERM [ ('+'|'-') TERM ]
 TERM ::= MUL [ ('*'|'/') MUL ]
 MUL ::= NUMBER | '(' EXPR ')'
 NUMBER ::= DIGIT [ DIGIT ]
 DIGIT ::= '0' ... '9'

just write the functions to parse each part (or use boost::spirit) and you will get your tree



来源:https://stackoverflow.com/questions/4121812/building-expression-tree

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