我目前正在创建一个表达式树,并且可以从infix->树开始。但是,由于负号,我很难从树 - >中缀表示法出发。
如何在从expressionTree转换为中缀表示法时确定何时为负号添加括号?
例如,将1-(1 + 1)转换为中缀将要求您在负号后添加括号。
转换1-1 *(1 + 1)不需要在负号后添加括号。 (虽然我可以,但我希望尽量减少括号的数量)
我目前用于确定括号的算法是:
int opValue() //determines the level precedence of current node
if (node is addition/subtraction) return 0
if (node is multiplication/division) return 1
if (node is exponentiation) return 2
else return 4 //implies it is not an operator
void printInfix()
if (leftNode is not empty)
if (currentNode is an operator and has a greater opVal than leftNode)
print "("
leftNode.printInfix()
print ")"
else
leftNode.printInfix()
print currentNode
if (rightNode is not empty)
if (currentNode is an operator and has a greater opVal than rightNode
or if it is a subtraction operator and the next node's opVal is 0)
print "("
rightNode.printInfix()
print ")"
else
right.printInfix()
这样的东西对于1-(1 + 1)+1不起作用,因为它不能正确地确定它何时需要括号。该表达式将转换为1 - ((1 + 1)+1)。
编辑:最后决定回到这一点。决定尝试这种方法。将报告是否有效:
if (node is multiplication/addition)
if (left is an operator of higher precedence) add parenthesis and output left
else output left
output node
if (right is an operator of higher precedence) add parenthesis and output right
else output right
/////////Non-commutative operators//////////////////////////
else if (node is subtraction)
if (left is an operator of higher precedence) add parenthesis and output left
else if (left is not NULL) output left
output node
if (right is an operator) add parenthesis and output right
else output right
///////////////////////////////////////////////////////////
else if (node is division/power)
if (left is an operator of higher precedence) add parenthesis and output left
else output left
output node
if (right is an operator) add parenthesis and output right
else output node
else //it is not a operator, or it is a constant, function, or variable
output node
return stream