C++ Binary Expression Tree: How do I print an infix expression with appropriate parentheses?
<p>Right now I have this simple print algorithm that prints perfect parentheses. The problem is, the parentheses aren't always necessary, and I need to figure out how to not print them when they aren't needed.</p>

<p>My current function:</p>

<pre><code>void printIn(Node* t){

if(t!= NULL) {
    if(isleafNode(t))
        cout &lt;&lt; t-&gt;element;
    else {      
        cout &lt;&lt; "(";
        printIn(t-&gt;left);
        cout &lt;&lt; t-&gt;data;
        printIn(t-&gt;right);
        cout &lt;&lt; ")";
        }
  }
</code></pre>

<p>The problem here is that some postfix expressions, such as
2 50 + 8 +
can be printed in infix as 2 + 50 + 8 instad of ((2 + 50) + 8))</p>

<p>Here is a chart of postfix to infix how it should look. Mine just adds parentheses around the whole outside, and to all addition no matter what.</p>

<pre><code>4 50 6 + +           4 + ( 50 + 6 )
4 50 + 6 +           4 + 50 + 6
4 50 + 6 2 * +       4 + 50 + 6 * 2
4 50 6 + + 2 *       ( 4 + ( 50 + 6 ) ) * 2
a b + c d e + * *    ( a + b ) * ( c * ( d + e ) )
</code></pre>

<p>Here is a chart of how mine look:</p>

<pre><code>4 50 6 + +           ( 4 + ( 50 + 6 ))
4 50 + 6 +           ( ( 4 + 50 ) + 6)
4 50 + 6 2 * +       ( ( 4 + 50 ) + ( 6 * 2 ) )
4 50 6 + + 2 *       ( ( 4 + ( 50 + 6 ) ) * 2 )
a b + c d e + * *    ( ( a + b) * ( c * ( d + e ) ) )
</code></pre>

<p>How can I fix my algorithm to eliminate extra parentheses?
p
Keep in mind I do have a getPrecedence(string) function that returns 1 for high precedence (* or /) and 0 for low precedence (+ or -)</p>