我有代码可以从infix生成后缀表达式,并从后缀符号生成表达式树。问题是,如果我给它一个像45 15 * 3这样的表达式,它将给我的结果是1而不是9,因为它是先解树的最深层。有没有其他的遍历方法可以让我正确地评估这个表达式?
def evaluate(self):
if not self.is_empty():
if not infix_to_postfix.is_operator(self._root):
return float(self._root)
else:
A = self._left.evaluate()
B = self._right.evaluate()
if self._root == "+":
return A + B
elif self._root == "-":
return A - B
elif self._root == "*":
return A * B
elif self._root == "/":
return A / B
def InfixToPostfix(exp: str):
exp = exp.replace(" ", "")
S = Stack()
postfix = ""
j = 0
for i in range(len(exp)):
if is_operand(exp[i]):
if i + 1 <= len(exp) - 1 and is_operand(exp[i+1]):
continue
else:
j = i
while j - 1 >= 0 and is_operand(exp[j - 1]):
if is_operand(exp[j]):
j -= 1
else:
break
postfix += exp[j:i + 1] + " "
elif is_operator(exp[i]):
while not S.is_empty() and S.top() != "(" and \ HasHigherPrecedence(S.top(), exp[i]):
if is_operator(S.top()):
postfix += S.top() + " "
else:
postfix += S.top()
S.pop()
S.push(exp[i])
elif exp[i] == "(":
S.push(exp[i])
elif exp[i] == ")":
while not S.is_empty() and S.top() != "(":
if is_operator(S.top()):
postfix += S.top() + " "
else:
postfix += S.top()
S.pop()
else:
print("There's an invalid character")
return
while not S.is_empty():
if S.top() == '(':
S.pop()
continue
if is_operator(S.top()):
postfix += S.top() + " "
else:
postfix += S.top()
S.pop()
return postfix
def HasHigherPrecedence(op1: str, op2: str):
op1_weight = get_operator_weight(op1)
op2_weight = get_operator_weight(op2)
return op1_weight > op2_weight
你的例子45 15 * 3的后缀表达式将是。
45 15 / 3 *
所以生成的树会是这样的
*
/ 3
45 15
所以你的遍历算法看起来是正确的 因为它会做45 15 = 3, 然后3 * 3 = 9.
在你的postfix生成器中,这个问题其实是非常小的。具体来说,在函数HasHigherPrecedence中,你应该返回的是 op1_weight >= op2_weight
. 应该是大于或等于,因为在这种运算符具有相同优先级的例子中,应该按照它们出现的顺序执行。所以,除法会先被执行。