I'm creating an expression tree that reads in postfix notation and converts it and prints it out into infix notation. I was wondering how would I go about correctly distributing parentheses and balancing them properly.

I'm creating an expression tree that reads in postfix notation and converts it and prints it out into infix notation. I was wondering how would I go about correctly distributing parentheses and balancing them properly.

normal expression: a+b-(c*d)
postfix: ab+cd*-
input | stack values
-----------------------------------
a | a (push a)
b | b,a (push b)
+ | (a+b) (pop twice and push (a+b))
c | c,(a+b) (push c)
d | d,c,(a+b) (push d)
* | (c*d), (a+b) (pop twice and push (c*d))
- | (a+b)-(c*d) (pop twice and push (a+b)-(c*d))
this is the final expression

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.