如何在树中添加“(”和“)”,表示一个完全括弧的中缀表达式,最终(下一个赋值)将被区分

时间:2019-03-26 06:21:29

标签: python tree

在下面的代码中,每次输出")"

输入:

((A+B)*((C-D)/(E^F)))

预期输出:

((A+B)*((C-D)/(E^F)))
A+B*C-D/E^F

我的输出:

)

我的代码:

class Et:
  def __init__(self , value):
        self.value = value
        self.left = None
        self.right = None
  def isOperator(c):
    if (c == '+' or c == '-' or c == '*' or c == '/' or c == '^' ):
        return True
    else:
        return False
  def inorder(t):
    if t is not None:
        inorder(t.left)
        print (t.value)
        inorder(t.right)
  def constructTree(postfix):
    stack = []
    for char in postfix :
        if not isOperator(char):
            t = Et(char)
            stack.append(t)
        else:
            t = Et(char)
            t1 = stack.pop()
            t2 = stack.pop()
            t.right = t1
            t.left = t2
            stack.append(t)
    t = stack.pop()
    return t
postfix = "((A+B)*((C-D)/(E^F)))"
r = constructTree(postfix)
inorder(r)

0 个答案:

没有答案