美文网首页
二叉树解析数学表达式

二叉树解析数学表达式

作者: withism | 来源:发表于2018-01-21 02:35 被阅读39次

    from pythonds.basic.stack import Stack

    from pythonds.trees.binaryTree import BinaryTree

    def buildParseTree(fpexp):

        fplist = fpexp.split()

        pStack = Stack()

        eTree = BinaryTree('')

        pStack.push(eTree)

        currentTree = eTree

        for i in fplist:

            if i == '(':

                currentTree.insertLeft('')

                pStack.push(currentTree)

                currentTree = currentTree.getLeftChild()

            elif i not in ['+', '-', '*', '/', ')']:

                currentTree.setRootVal(int(i))

                parent = pStack.pop()

                currentTree = parent

            elif i in ['+', '-', '*', '/']:

                currentTree.setRootVal(i)

                currentTree.insertRight('')

                pStack.push(currentTree)

                currentTree = currentTree.getRightChild()

            elif i == ')':

                currentTree = pStack.pop()

            else:

                raise ValueError

        return eTree

    pt = buildParseTree("( ( 10 + 5 ) * 3 )")

    pt.postorder()  #defined and explained in the next section

    相关文章

      网友评论

          本文标题:二叉树解析数学表达式

          本文链接:https://www.haomeiwen.com/subject/qonxaxtx.html