开发者

Displaying the postfix/prefix expression as a parse tree using C/C++

I have successfully converted infix expression to postfix expression and was also able to evaluate the postfix expression but I am fac开发者_运维技巧ing problem in generating a parse tree for the same with C/C++

My output :

           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

I also require to display: Syntax tree

               +          
             /   \                                
          *       a                               
         /   \                                               
        b     c       

Any feedback would be very helpful in my project.

Thanks in Adv.

@LD: Thanks for your consistent help. I need the pseudocode in turbo C. I don't know Ruby.


It's much easier to "draw" them like the following:

+
  a
  *
    b
    c

Or, if you want to use simple character graphics (I've changed the + and * operators to Add and Mul, to avoid clashing with the graphics):

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

The trick to doing this is possible draw a subtree in isolation (e.g. the mul tree), and then draw it with suitable prefixes when drawing the outer tree.

In fact, if you are familiar with C++ stream buffers, you could create a prefixing stream buffer that handles the prefixes and simply print the inner tree.

The big difference compared to the style you suggested is that your style simply doesn't scale. If, for example the top operator would have two big subtrees, they would have been drawn extremely far apart.

EDIT: A slightly more complex tree could be drawn like this:

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

EDIT: On request, here comes some pseudo-code (which, incidentally, is acceptable by a Ruby interpreter). You must, however, use a suitable C++ data structure to represent the tree.

# 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"]])
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜