在从中创建表达式树时是否需要将中缀表示法转换为后缀?

Tur*_*lov 1 infix-notation expression-trees postfix-notation data-structures

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

Mat*_*ans 5

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

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

这是 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")
Run Code Online (Sandbox Code Playgroud)

这打印:

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

在这里尝试一下:

https://ideone.com/RyusvI

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