使用C / C ++将后缀/前缀表达式显示为解析树

时间:2011-04-20 06:22:54

标签: c++ c syntax tree

我已成功将中缀表达式转换为后缀表达式,并且还能够评估后缀表达式,但我在使用C / C ++生成解析树时遇到问题

我的输出:

           enter the expression string a+b*c
           the expression is correct
           the postfix expression is - abc *+
           enter the value of a-1
           enter the value of b-2
           enter the value of c-3
           the postfix expression is -abc*+
           result= 7

我还需要显示:语法树

               +          
             /   \                                
          *       a                               
         /   \                                               
        b     c       

任何反馈对我的项目都非常有帮助。

感谢Adv。

@LD:感谢您的一贯帮助。我需要turbo C中的伪代码。我不知道Ruby。

1 个答案:

答案 0 :(得分:4)

如下所示“绘制”它们要容易得多:

+
  a
  *
    b
    c

或者,如果您想使用简单的字符图形(我已将+*运算符更改为AddMul,以避免与图形冲突):

Add
+-- a
+-- Mul
    +-- b
    +-- c

这样做的诀窍是可以单独绘制一个子树(例如mul树),然后在绘制外树时用合适的前缀绘制它。

实际上,如果您熟悉C ++流缓冲区,则可以创建一个前缀流缓冲区来处理前缀并简单地打印内树。

与您建议的风格相比,最大的区别在于您的风格根本无法扩展。例如,如果顶级运算符有两个子树,那么它们将被绘制得相距甚远。

编辑:可以像这样绘制一个稍微复杂的树:

Add
+---Sub
|    +---Div
|    |    +---p
|    |    +---q
|    +---y
+---Mul
     +---b
     +---c

编辑:根据要求,这里有一些伪代码(顺便提一下,Ruby解释器可以接受)。但是,您必须使用合适的C ++数据结构来表示树。

# Return the drawn tree as an array of lines.
#
# node ::= string
# node ::= [string, node, node]
def render_tree(node, prefix0 = "", prefix = "")
  if (node.is_a?(String))
    puts prefix0 + node         # Value
  else
    puts prefix0 + node[0]      # Operator
    render_tree(node[1], prefix  + "+---", prefix + "|    ")
    render_tree(node[2], prefix  + "+---", prefix + "     ")
  end
end
render_tree(["Add", ["Sub", ["Div", "p", "q"], "y"], ["Mul", "b", "c"]])