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

|| 我已经成功地将后缀表达式转换为后缀表达式,并且还能够评估后缀表达式,但是我在使用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       
任何反馈将对我的项目非常有帮助。 感谢高级。 @LD:感谢您的一贯帮助。我需要Turbo C中的伪代码。我不了解Ruby。
已邀请:
像下面这样“绘制”它们要容易得多:
+
  a
  *
    b
    c
或者,如果要使用简单的字符图形(为了避免与图形冲突,我将
+
和ѭ4to运算符更改为
Add
Mul
):
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\"]])

要回复问题请先登录注册