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()
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()
def build_tree_condition(elements): if len(elements) == 1: return elements[0] tree = BinaryTree('') for i in range(len(elements)): if type(elements[i]) is BinaryTree: if tree.getRootVal() == '': tree.insertLeft(elements[i]) else: tree.insertRight(elements[i]) elif tree.getRootVal() in ['AND', 'OR', 'or', 'and']: new_tree = BinaryTree('') new_tree.setRootVal(elements[i]) new_tree.insertLeft(tree) tree = new_tree else: tree.setRootVal(elements[i]) return tree
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
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
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
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
def preorder(tree: BinaryTree): # 前序遍历 if tree: print(tree.getRootVal()) preorder(tree.getLeftChild()) preorder(tree.getRightChild())
def postorder(tree: BinaryTree): # 后序遍历 if tree: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print(tree.getRootVal())
def inorder(tree: BinaryTree): # 中序遍历 if tree: inorder(tree.getLeftChild()) print(tree.getRootVal()) inorder(tree.getRightChild())
def build_tree_expression(elements): stack = Stack() tree = BinaryTree('') if len(elements) == 1: tree.setRootVal(elements[0]) return tree stack.push(tree) for i in range(len(elements)): if (elements[i] == '(') or (i == 0): tree.insertLeft('') if elements[i] == '(': stack.push("(") stack.push(tree) tree = tree.getLeftChild() if elements[i] != '(': tree.setRootVal(elements[i]) parent = stack.pop() tree = parent elif elements[i] not in ['+', '-', '*', '/', ')']: tree.setRootVal(elements[i]) parent = stack.pop() tree = parent elif elements[i] in ['+', '-', '*', '/']: sign = elements[i] if tree.getRootVal() in ['+', '-', '*', '/']: if sign in ['+', '-'] or elements[i - 1] == ')': temp = BinaryTree('') parent = stack.pop() if stack.size() == 0: temp.insertLeft(parent) parent = temp tree = parent stack.push(parent) elif parent == "(": temp.insertLeft(tree) parent = stack.pop() parent.insertRight(temp) stack.push(parent) stack.push("(") tree = parent.getRightChild() else: temp.insertLeft(tree) parent.insertRight(temp) stack.push(parent) tree = parent.getRightChild() elif sign in ['*', '/']: rChild = tree.getRightChild() rChild.insertLeft(rChild.getRootVal()) tree = rChild tree.setRootVal(elements[i]) tree.insertRight('') stack.push(tree) tree = tree.getRightChild() elif elements[i] == ')': parent = "" while parent != "(": parent = stack.pop() if parent == "(": tree = stack.pop() stack.push(tree) if i + 1 == len(elements): for j in range(stack.size()): parent = stack.pop() tree = parent return tree
r = BinaryTree('a') print(r.getRootVal()) #a print(r.getLeftChild()) #None r.insertLeft('b') print(r.getLeftChild()) #<__main__.BinaryTree object at 0x0000000005FFC780> print(r.getLeftChild().getRootVal()) #b r.insertRight('c') print(r.getRightChild()) #<__main__.BinaryTree object at 0x0000000005DA2898> print(r.getRightChild().getRootVal()) #c r.getRightChild().setRootVal('hello') print(r.getRightChild().getRootVal()) from pythonds.basic.stack import Stack from pythonds.trees.binaryTree import BinaryTree 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