构建表达式二叉树

# -*- coding: cp936 -*-
#构建表达式二叉树
import Stack

#if 'ch' is opreator,then return True,otherwise return False
def isOperator(ch):
    if '+' == ch or '-' == ch or\
       '*' == ch or '/' == ch or\
       '(' == ch or ')' == ch or\
       '#' == ch:
        return True

    return False
#compare opt1/opt2, return 1(opt1>opt2),return 0(opt1==opt2),
#return -1(opt1<opt2)
def isOpt1ExceedOpt2(opt1,opt2):
    if '+' == opt1 or '-' == opt1:
        if '*' == opt2 or '/' == opt2 or '(' == opt2:
            return -1
        else:
            return 1
    elif '*' == opt1 or '/' == opt1:
        if '(' == opt2:
            return -1
        else:
            return 1
    elif '(' == opt1:
        if ')' == opt2:
            return 0
        else:
            return -1
    elif ')' == opt1:
        if '(' == opt2:
            return 0
        else:
            return 1
    
    elif '#' == opt1:
        return 1

def createNewInnerNode(opd1,opd2,opt):
    node = []
    node.append(opd2)
    node.append(opt)
    node.append(opd1)
    return node

def createExpBinTree(exp):
    cursor = 0

    operatorStack = Stack.Stack()
    operandStack = Stack.Stack()
    
    while cursor < len(exp):
        print '--------------------------------------------------------------------------------'
        print 'operatorStack:',
        operatorStack.printStack()
        print 'operandStack :',
        operandStack.printStack()
        if isOperator(exp[cursor]):
            if operatorStack.isEmpty():
                operatorStack.push(exp[cursor])
                cursor = cursor + 1
            else:
                flag = isOpt1ExceedOpt2(operatorStack.top(),exp[cursor])
                if 1 == flag:
                    innerNode = createNewInnerNode(operandStack.pop(),
                                                   operandStack.pop(),
                                                   operatorStack.pop())
                    operandStack.push(innerNode)
                elif 0 == flag:
                    operatorStack.pop()
                    cursor = cursor + 1
                else:
                    operatorStack.push(exp[cursor])
                    cursor = cursor + 1
        else:
            operandStack.push(list(exp[cursor]))
            cursor = cursor + 1
    print '--------------------------------------------------------------------------------'    
    return operandStack.pop()

print createExpBinTree("a+(b+c)*d-e#")
原文地址:https://www.cnblogs.com/chencheng/p/3137386.html