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.

My current function:

```
void printIn(Node* t){
if(t!= NULL) {
if(isleafNode(t))
cout << t->element;
else {
cout << "(";
printIn(t->left);
cout << t->data;
printIn(t->right);
cout << ")";
}
}
```

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))

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.

```
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 ) )
```

Here is a chart of how mine look:

```
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 ) ) )
```

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 -)

When printing an expression tree in infix form you only need to print parenthesis around sub-expressions (i.e. children) where the operator has a lower precedence than the operator of the main (i.e. parent) expression.

As an example, take the following expression tree (in postfix notation) and its infix form.

```
4 5 6 + 7 * + 4 + (5 + 6) * 7
```

Note that a parenthesis is needed around 5 + 6 since the operator of the sub-expression 5 6 + has lower precedence than the operator of the main expression 5 6 + 7 * but it is not needed for the sub-expression 5 6 + 7 * since the operator has higher precedence than the operator of the main expression 4 5 6 + 7 * +

Using this information it is easy to modify the algorithm in the question to avoid parenthesis when they are not needed. Note that since there are no parent pointers in the tree it is easier to make the parent check if any of the children needs parenthesis than to make the node put parenthesis around itself.

Licensed under: CC-BY-SA with attribution

Not affiliated with Stack Overflow

Is this KB legal? Yes, learn why