【问题标题】:Is it necessary to convert infix notation to postfix when creating an expression tree from it?从中创建表达式树时是否需要将中缀表示法转换为后缀?
【发布时间】:2019-12-20 00:21:57
【问题描述】:

我想创建一个表达式树给定中缀形式的表达式。是否需要先将表达式转换为后缀,然后再创建树?我知道这在某种程度上取决于问题本身。但假设它是具有未知数和运算符的简单数学函数表达式:/ * ^ + -.

【问题讨论】:

    标签: data-structures expression-trees postfix-notation infix-notation


    【解决方案1】:

    没有。如果要构建表达式树,则不必先将表达式转换为后缀。在解析时构建表达式树会更简单。

    我通常为表达式编写递归下降解析器。在这种情况下,每个递归调用只返回它解析的子表达式的树。如果您想使用迭代式调车场式算法,那么您也可以这样做。

    这是一个简单的 Python 递归下降解析器,它可以生成一棵带有节点元组的树:

    import re
    
    def toTree(infixStr):
        # divide string into tokens, and reverse so I can get them in order with pop()
        tokens = re.split(r' *([\+\-\*\^/]) *', infixStr)
        tokens = [t for t in reversed(tokens) if t!='']
        precs = {'+':0 , '-':0, '/':1, '*':1, '^':2}
    
        #convert infix expression tokens to a tree, processing only
        #operators above a given precedence
        def toTree2(tokens, minprec):
            node = tokens.pop()
            while len(tokens)>0:
                prec = precs[tokens[-1]]
                if prec<minprec:
                    break
                op=tokens.pop()
    
                # get the argument on the operator's right
                # this will go to the end, or stop at an operator
                # with precedence <= prec
                arg2 = toTree2(tokens,prec+1)
                node = (op, node, arg2)
            return node
    
        return toTree2(tokens,0)
    
    print toTree("5+3*4^2+1")
    

    打印出来:

    ('+', ('+', '5', ('*', '3', ('^', '4', '2'))), '1')

    在这里试试:

    https://ideone.com/RyusvI

    请注意,上述递归下降风格是编写了许多解析器的结果。现在我几乎总是以这种方式解析表达式(递归部分,而不是标记化)。它与表达式解析器一样简单,并且可以轻松处理括号以及从右到左关联的运算符,如赋值运算符。

    【讨论】:

      猜你喜欢
      • 2011-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-12
      • 2014-08-26
      • 1970-01-01
      • 2018-01-29
      • 1970-01-01
      相关资源
      最近更新 更多