Пример #1
0
 def insert_right(self, new_node):
     if self.right_child == None:
         self.right_child = BinaryTree(new_node)
     else:
         t = BinaryTree(new_node)
         t.right_child = self.right_child
         self.right_child = t
Пример #2
0
 def insert_left(self, new_node):
     if self.left_child == None:
         self.left_child = BinaryTree(new_node)
     else:
         t = BinaryTree(new_node)
         t.left_child = self.left_child
         self.left_child = t
Пример #3
0
def buildParseTree(fpexp):
    fplist = fpexp.split()  #splitting a string of expression into list
    #(type list)
    pStack = Stack()  #create empty stack
    #(type 'instance')
    eTree = BinaryTree('')  #top root value
    #(type 'instance')
    pStack.push(eTree)  #pushed current root into the stack
    print pStack.size()
    currentTree = eTree  #current position at a time
    #(type 'instance')

    for i in fplist:
        if i == '(':
            currentTree.insertLeft('')  #inserts an empty node as a leftChild
            #print currentTree
            pStack.push(currentTree)  #pushes current tree into the stack
            print 'StackSize: {},  root: {}      iteration(push): {} '.format(
                pStack.size(), currentTree.getRootVal(), i)
            currentTree = currentTree.getLeftChild(
            )  #sets current position to the leftChild

        elif i not in ['+', '-', '*', '/', ')']:
            print '-----before root: {} '.format(currentTree.getRootVal())
            currentTree.setRootVal(
                int(i)
            )  #we are located at the node so set  the root value to the number
            #parent = pStack.pop()  #???
            #print 'StackSize: {},  parent: {}     iteration(pop): digits'.format(pStack.size(), parent.getRootVal())
            #currentTree = parent  #this sets the current position to the parent node
            currentTree = pStack.pop()
            print 'StackSize: {},     iteration(pop): digits'.format(
                pStack.size())
            print '-----after root: {} '.format(currentTree.getRootVal())

        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(
                i)  #set the value to the operator for "currentTree"
            currentTree.insertRight('')  # descend to the right child
            pStack.push(
                currentTree
            )  #push the new tree to the stack (will it push last updated node or the whole tree? Will it souble it?)
            print 'StackSize: {}, root: {}      iteration(push): {}'.format(
                pStack.size(), currentTree.getRootVal(), i)
            currentTree = currentTree.getRightChild(
            )  # this set the current position to the rightChild

        elif i == ')':
            currentTree = pStack.pop()
            print 'StackSize: {}, root: {}      iteration(pop)'.format(
                pStack.size(), currentTree.getRootVal(), i)

        else:
            raise ValueError
    print 'eTee root:  {} '.format(eTree.getRootVal())
    return eTree
Пример #4
0
def postorder_evaluate(tree: BinaryTree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }

    if tree:
        res1 = postorder_evaluate(tree.getLeftChild())
        res2 = postorder_evaluate(tree.getRightChild())
        if res1 and res2:
            return opers[tree.getRootVal()](res1, res2)
        else:
            return tree.getRootVal()
Пример #5
0
def print_exp(tree: BinaryTree):
    # 优化后的方法,去掉每个数字的左右括号
    sVal = ''

    if tree:
        str_val = str(tree.getRootVal())
        result = print_exp(tree.getLeftChild()) + str_val + print_exp(
            tree.getRightChild())

        if str_val.isnumeric():
            sVal = result
        else:
            sVal = '(' + result + ')'

    return sVal
Пример #6
0
 def __init__(self, rule, globals=globals()):
     tokens = rule.split()
     pStack = Stack()
     self.tree = BinaryTree('')
     pStack.push(self.tree)
     current_tree = self.tree
     is_func_args = False
     self.globals = globals
     for token in tokens:
         # Open bracket.
         if token == '(':
             if is_func_args:
                 parent = pStack.pop()
                 current_tree = parent
             current_tree.insertLeft('')
             pStack.push(current_tree)
             current_tree = current_tree.getLeftChild()
             is_func_args = False
         # Function name or arguments.
         elif token.lower() not in ['and', 'or', ')']:
             if not is_func_args:
                 current_tree.setRootVal((token, []))
                 is_func_args = True
                 continue
             current_tree.key[1].append(token)
         elif token.lower() in ['and', 'or']:
             if is_func_args:
                 parent = pStack.pop()
                 current_tree = parent
             current_tree.setRootVal(token)
             current_tree.insertRight('')
             pStack.push(current_tree)
             current_tree = current_tree.getRightChild()
             is_func_args = False
         elif token == ')':
             if is_func_args:
                 parent = pStack.pop()
                 current_tree = parent
             current_tree = pStack.pop()
             is_func_args = False
         else:
             raise ValueError
     self.tree = current_tree
     # If we have only 1 node (Example: "func1 arg1"), then
     # the root node is empty. Make it left child which is not empty.
     if self.tree.getRightChild() is None and self.tree.getLeftChild(
     ) is not None:
         self.tree = self.tree.getLeftChild()
Пример #7
0
def buildParseTree(fpexp):
    breakList = listAdjust(fpexp)
    #fplist = breakList.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    # Checks if item passed in from 'fpexp' contains integers or mathemateical operators
    for i in breakList:
        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
Пример #8
0
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
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 [
                '+', '-', '*', '/', ')', '&&', '|', '<', '>', '!', '==', '!=',
                '<=', '>=', 'is', 'and', 'or'
        ]:
            currentTree.setRootVal(i)
            parent = pStack.pop()
            currentTree = parent
        elif i in [
                '+', '-', '*', '/', ')', '&&', '|', '<', '>', '!', '==', '!=',
                '<=', '>=', 'is', 'and', 'or'
        ]:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Пример #10
0
def buildParseTree(equation):
    """
    input: a exquation expression, with parenthesis regulated
    output: a tree with postorder traversal
    """
    equationList = equation.split()
    pStack = Stack()
    eTree = BinaryTree('')
    currentTree = eTree
    pStack.push(eTree)
    for i in equationList:
        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
Пример #11
0
def build_parse_tree(fpexp):
    fplist = fpexp.split()

    pstack = Stack()

    etree = BinaryTree("")

    pstack.push(etree)
    current_tree = etree

    for i in fplist:
        if i == '(':
            current_tree.insertLeft("")
            pstack.push(current_tree)
            current_tree = current_tree.getLeftChild()

        elif i not in ['+', '-', '*', '/', ')']:
            current_tree.setRootVal(int(i))
            parent = pstack.pop()
            current_tree = parent

        elif i in ['+', '-', '*', '/', ')']:
            current_tree.setRootVal(i)
            current_tree.insertRight("")
            pstack.push(current_tree)
            current_tree = current_tree.getRightChild()

        elif i == ')':
            current_tree = pstack.pop()

        else:
            raise ValueError

        return etree
Пример #12
0
def buildParseTree(fpexp):
    fplist = list(fpexp.replace(' ', ''))
    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
Пример #13
0
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 in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        elif i not in ['+', '-', '*', '/', ')']:
            try:
                currentTree.setRootVal(int(i))
                parent = pStack.pop()
                currentTree = parent
            except ValueError:
                raise ValueError("token'{}'is not a valid integer".format(i))
        return eTree
Пример #14
0
def p_tree_comparison(p):
    '''tree_comparison :  tree_expression operator_comparison tree_expression'''

    p[0] = BinaryTree('')
    p[0].insertLeft(build_tree_expression(p[1]))
    p[0].setRootVal(p[2])
    p[0].insertRight(build_tree_expression(p[3]))
Пример #15
0
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()
            ##extending to add boolean function
        elif i not in ['+', '-', '*', '/', ')','>','<','==','!']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
            #extending to add boolean function
        elif i in ['+', '-', '*', '/','>','<','==','!',')']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
            
        else:
            raise ValueError
    return eTree
def buildParseTree(fpexp, aviableOperators=["and", "And", "or", "Or", ")"]):
    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 aviableOperators:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in aviableOperators:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Пример #17
0
def evaluate(parseTree: BinaryTree):
    opers = {
        '+': operator.add,
        '-': operator.sub,
        '*': operator.mul,
        '/': operator.truediv
    }

    leftC = parseTree.getLeftChild()
    rightC = parseTree.getRightChild()

    if leftC and rightC:
        fn = opers[parseTree.getRootVal()]
        return fn(evaluate(leftC), evaluate(rightC))
    else:
        return parseTree.getRootVal()
Пример #18
0
def parse_tree(str):
    str_split = str.split()
    node_stack = Stack()
    output_tree = BinaryTree('')
    node_stack.push(output_tree)
    current_root = output_tree
    for each_chara in str_split:
        if each_chara == '(':
            # for ( in the string
            current_root.insertLeft('')
            node_stack.push(current_root)
            # we conduct all the operations on the current node, and the output node
            # is just used for store the first node, which is used to output
            current_root = current_root.getLeftChild()
        elif each_chara not in ['+', '-', '*', '/', ')']:
            # a number to be used for calculation
            current_root.setRootVal(int(each_chara))
            current_parent = node_stack.pop()
            current_root = current_parent
        elif each_chara in ['+', '-', '*', '/']:
            # if a operator
            current_root.setRootVal(each_chara)
            current_root.insertRight('')
            node_stack.push(current_root)
            current_root = current_root.getRightChild()
        elif each_chara == ")":
            current_root = node_stack.pop()
        else:
            raise ValueError
    return output_tree
Пример #19
0
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(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
Пример #20
0
def buildParseTree(formula):
    formulalist = formula.split()  #['(','3','+','(','4','*','5',')',')']
    rootStack = Stack()  #用于跟踪父节点
    Tree = BinaryTree('')  #创建一个二叉树
    rootStack.push(Tree)
    currentTree = Tree
    for i in formulalist:
        if i == '(':
            currentTree.insertLeft('')
            rootStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = rootStack.pop()
            cerrentTree = parent
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            rootStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = rootStack.pop()
        else:
            raise ValueError  #raise的参数必须是一个异常实例或者一个异常类:ValueError无效参数
    return Tree
Пример #21
0
    def build_parse_tree(fpexpr):
        fp_list = fpexpr.split()
        pstack = Stack()
        eTree = BinaryTree('')
        pstack.push(eTree)
        current_node = eTree

        for i in fp_list:
            if i == '(':
                current_node.insert_left('')
                pstack.push(current_node)
                current_node = current_node.get_left_child()
            elif i not in ['+', '-', '*', '/', ')']:
                current_node.set_root_val(int(i))
                parent = pstack.pop()
                current_node = parent
            elif i in ['+', '-', '*', '/']:
                current_node = set_root_val(i)
                current_node.insert_right('')
                pstack.push(current_node)
                current_node = current_node.get_right_child()
            elif i == ')':
                current_node = pstack.pop()
            else:
                raise ValueError
        return eTree
Пример #22
0
def buildParseTree(fpexp):
    fplist = fpexp.split()
    # 输入时必须有空格
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    # pStack 用于存储父节点 调用时pop()
    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
Пример #23
0
def buildParseTree(fpexp):
    fplist = fpexp.split()
    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree

    for item in fplist:
        if item == "(":
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif item.isnumeric():
            currentTree.setRootVal(int(item))
            currentTree = pStack.pop()
        elif item in '+-/*':
            currentTree.setRootVal(item)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif item == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError("token '{}' is not a valid integer".format(item))

    return eTree
Пример #24
0
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 in ["+", "-", "*", "/"]:
            currentTree.setRootVal(i)
            currentTree.insertRight("")
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i not in ["+", "-", "*", "/", ")"]:
            currentTree.setRootVal(i)
            parent = pStack.pop()
            currentTree = parent
        elif i == ")":
            currentTree = pStack.pop()
        else:
            raise ValueError

    return eTree
Пример #25
0
def buildParseTree(fpexp):
    fplist = str(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.upper() in ['+', '-', '*', '/', 'TRUE',
                           'FALSE']:  #added true and false
            currentTree.setRootVal(i.upper())
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i == ')':
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Пример #26
0
def construyeArbol(sufijoInv):
    arbol = Arbol()
    raiz = Nodo(sufijoInv[0], 'raiz')
    arbol.agregar(raiz)
    for a in range(1, len(sufijoInv)):
        nodo = Nodo(sufijoInv[a])
        if arbol.nodos[-1].derecha is None:
            arbol.agregar(nodo, 'derecha')
        else:
            arbol.agregar(nodo, 'derecha')
Пример #27
0
def buildParseTree(fpexp):
    """
    fpexp = "( ( 10 + 5 ) * 3 )"
    pt = buildParseTree(fpexp)

    """
    fplist = fpexp.split()
    ## 用來儲存父節點
    ## parent stack
    pStack = Stack()
    ## 因為 Class() 是傳址 (reference type)
    ## 所以 eTree 和 currentTree 會是同一個 address
    ## 因此對 currentTree 所做的操作,會同樣影響 eTree!
    ##
    ## 附註:int, ... 是傳值 (value type)
    eTree = BinaryTree('')
    ## pStack: 紀錄父節點
    pStack.push(eTree)
    ## 傳址 (reference type)
    currentTree = eTree

    operator = ["+", "-", "*", "/"]
    not_numbers = operator + ['(', ')']
    for i in fplist:
        if i == "(":
            ## 插入左子樹,並將 current 移到左子樹
            ## 此時 eTree 亦同樣插入左子樹
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in not_numbers:
            ## 如果是數字
            ## 則把該節點的值設定為 i
            ## 並利用 pStack 退回到該節點的父節點
            currentTree.setRootVal(int(i))
            parent = pStack.pop()
            currentTree = parent
        elif i in operator:
            ## 如果是運算子
            ## 則設定該節點為運算子後
            ## 插入右子樹
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            pStack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ")":
            ## 如果是 ")"
            ## 再往上退到該節點的父節點
            currentTree = pStack.pop()
        else:
            raise ValueError

    return eTree
Пример #28
0
def set_tree(text):
    wtext = text.split()

    pStack = Stack()
    eTree = BinaryTree('')
    pStack.push(eTree)
    currentTree = eTree
    currentTree.insertLeft('')
    currentTree = currentTree.getLeftChild()
    currentTree.setRootVal('1')
    pStack.push(currentTree)

    for i in wtext:
        if BinaryTree.getRootVal(
                currentTree) == '1' and not currentTree.isLeaf():
            currentTree = pStack.pop()
            currentTree.insertRight('')
            currentTree = currentTree.getRightChild()
            currentTree.setRootVal('2')
            pStack.push(currentTree)
        if i == '(':
            currentTree.insertLeft('')
            pStack.push(currentTree)
            currentTree = currentTree.getLeftChild()
        elif i not in ['(', ')']:
            if currentTree.isLeaf():
                if BinaryTree.getRootVal(currentTree) != '':
                    currentTree = pStack.pop()
                    currentTree.insertRight('')
                    currentTree = currentTree.getRightChild()
                    currentTree.setRootVal(i)
                elif BinaryTree.getRootVal(currentTree) != None:
                    currentTree.setRootVal(i)
                pStack.push(currentTree)
        elif i == ')':
            currentTree = pStack.pop()
            currentTree = pStack.pop()
        else:
            raise ValueError
    return eTree
Пример #29
0
class BinaryTree(object):
    def __init__(self, root_obj):
        self.key = root_obj
        self.left_child = None
        self.right_child = None

    def insert_left(self, new_node):
        if self.left_child == None:
            self.left_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.left_child = self.left_child
            self.left_child = t

    def insert_right(self, new_node):
        if self.right_child == None:
            self.right_child = BinaryTree(new_node)
        else:
            t = BinaryTree(new_node)
            t.right_child = self.right_child
            self.right_child = t

    def get_right_child(self):
        return self.right_child

    def get_left_child(self):
        return self.left_child

    def get_root_val(self):
        return self.key

    def set_root_val(self, obj):
        self.key = obj

    def preorder(self):
        print(self.key)
        if self.left_child:
            self.left_child.preorder()
        if self.right_child:
            self.right_child.preorder()
Пример #30
0
def buildParseTree(expr):
    expr = expr.split()
    binaryTree = BinaryTree('')
    stack = Stack()
    stack.push(binaryTree)  # 避免空栈弹出时报错
    currentTree = binaryTree
    for i in expr:
        if i == '(':
            currentTree.insertLeft('')
            stack.push(currentTree)
            currentTree = binaryTree.getLeftChild()
        elif i not in ['+', '-', '*', '/', ')']:
            currentTree.setRootVal(int(i))  # 非数字int()就会报错
            currentTree = stack.pop()
        elif i in ['+', '-', '*', '/']:
            currentTree.setRootVal(i)
            currentTree.insertRight('')
            stack.push(currentTree)
            currentTree = currentTree.getRightChild()
        elif i == ')':
            currentTree = stack.pop()
        else:
            raise ValueError
    return binaryTree
Пример #31
0
# binary tree or not
from pythonds.trees.binaryTree import BinaryTree
prev=None
def isBinarySearchTree(root):
    global prev
    if root:
        if not isBinarySearchTree(root.leftChild):
            return False
        if (prev and prev.key>root.key):
            return False
        prev=root
        if not isBinarySearchTree(root.rightChild):
            return False
    return True

tree=BinaryTree(4)
tree.insertLeft(2)
tree.insertRight(5)
ls=tree.getLeftChild()
ls.insertLeft(1)
ls.insertRight(3)
print isBinarySearchTree(tree)


Пример #32
0
def build_parse_tree(fpexp):
    fplist = fpexp.split()
    for i in fplist:
        if i.__contains__('(') and i != '(':
            index = fplist.index(i)
            i_l = i.split('(')
            fplist[index] = i_l[-1]
            for j in range(len(i_l)-1):
                fplist.insert(index, '(')
        if i.__contains__(')') and i != ')':
            index = fplist.index(i)
            i_l = i.split(')')
            fplist[index] = i.split(')')[0]
            for j in range(len(i_l)-1):
                fplist.insert(index+1, ')')
    pstack = Stack()
    current_tree = BinaryTree('')
    current_tree.insertLeft('')
    pstack.push(current_tree)
    current_tree = current_tree.getLeftChild()
    for i in fplist:
        if i == '(':
            current_tree.insertLeft('')
            pstack.push(current_tree)
            current_tree = current_tree.getLeftChild()
        elif i not in ['and', 'or', ')']:
            current_tree.setRootVal(i)
            parent = pstack.pop()
            current_tree = parent

        elif i in ['and', 'or']:
            if current_tree.getRootVal() != "":
                pstack.push(current_tree)
                current_tree = BinaryTree('')
                current_tree.leftChild = pstack.pop()
            current_tree.setRootVal(i)
            current_tree.insertRight('')
            pstack.push(current_tree)
            current_tree = current_tree.getRightChild()
        elif i == ')':
            current_tree = pstack.pop()
        else:
            raise ValueError
    return current_tree
from pythonds.trees.binaryTree import BinaryTree
import operator

x = BinaryTree('*')
x.insertLeft('+')
l = x.getLeftChild()
l.insertLeft(4)
l.insertRight(5)
x.insertRight(7)


def printexp(tree):
  sVal = ""
  if tree:
      sVal = '(' + printexp(tree.getLeftChild())
      sVal = sVal + str(tree.getRootVal())
      sVal = sVal + printexp(tree.getRightChild())+')'
  return sVal

def postordereval(tree):
  opers = {'+':operator.add, '-':operator.sub, '*':operator.mul, '/':operator.truediv}
  res1 = None
  res2 = None
  if tree:
      res1 = postordereval(tree.getLeftChild())
      res2 = postordereval(tree.getRightChild())
      if res1 and res2:
          return opers[tree.getRootVal()](res1,res2)
      else:
          return tree.getRootVal()