简体   繁体   中英

postifx to infix binary expression tree (parenthesis) using stack

I have a program (c++) I'm writing where I'm converting a postfix expression to infix

Example Postfix: ab + cde + * * Converted to infix: ( a + b ) * ( c * ( d + e ) )

You do this by traversing "inorderly" through the binary expression tree

I have a recursiving function that prints out the expression properly, but I can't quite figure out how to place the paranthesis in the correct place. My best attempt was the result ( a + b ) * ( c * ( d + e //but I can't place the end parenthesis correctly without messing up other parts

This is the function that produced this result (and I'm pretty sure I need to rethink my strategy for consistent results:

//isHigher is a lamba function that checks for higher precedence operators (*, /)
//isoperator checks if its an operator (+, - , / * )
void BET::printInfixExpression(BinaryNode *n)
{
  if(n->left != NULL)
  {
    if(isOperator(n->left->element) && isHigher(n->element) && !isHigher(n->left->element))
      cout << "( ";
    if(isHigher(n->element) && !isOperator(n->left->element))
      cout << "( ";
    printInfixExpression(n->left);
  }
  if(isHigher(n->element) && isHigher(n->right->element))
    cout << ") ";
  cout << n->element << " ";
  if(isHigher(n->element) && isOperator(n->right->element) && !isHigher(n->right->element))
    cout << "( ";
  if(n->right != NULL)
  {
    printInfixExpression(n->right);
  }
}

This is the original function that outputs an infix with no parenthesis:

void BET::printInfixExpression(BinaryNode *n)
{
  if(n->left != NULL)
  {
    printInfixExpression(n->left);
  }
  cout << n->element << " ";

  if(n->right != NULL)
  {
    printInfixExpression(n->right);
  }
}

So my problem is getting the parenthesis placed correctly. Any help would be greatly appreciated, It's the weekend so my TA's/teacher haven't gotten back to me.

edit: Redundant parenthesis is not allowed. It has to be appropriately placed when necessary but not when it isn't necessary.

You don't need to know the operator precedence. It is already implicit in the postfix. You just need to put parentheses around every operand-operator-operand tuple as you output them. So for example, ab+ becomes (a+b), abc++ becomes (a+(b+c)). So just output a "(" at the beginning of printInfixExpression() and a ")" at the end of it. You will get redundant parentheses, but I don't see anything in your question about suppressing those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM