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 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
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
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
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
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): 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
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
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
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
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
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
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
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]))
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
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) for i in fplist: if i == '(': # 如果当前符号是“(”,添加一个新节点作为当前节点的左子节点,并且下降到左子节点 eTree.insertLeft('') pStack.push(eTree) eTree = eTree.getLeftChild() elif i not in ['+', '-', '/', '*', ')']: # 如果当前符号是数字,将当前节点的根值设置为该数字并返回父节点 eTree.setRootVal(int(i)) parent = pStack.pop() eTree = parent elif i in ['+', '-', '/', '*']: eTree.setRootVal(i) eTree.insertRight('') pStack.push(eTree) eTree = eTree.getRightChild() elif i == ')': eTree = pStack.pop() else: raise ValueError return eTree
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
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
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
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 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 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 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
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()
def buildParseTree(fpexp): fplist = fpexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree i = 0 while (i < len(fplist)): #print("Analyzing:",fplist[i]) if fplist[i] == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif fplist[i] in ['|', '.']: currentTree.setRootVal(Nodo(fplist[i])) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif fplist[i] in ["*>", "+>"]: #if fplist[i+1] == '>': currentTree.setRootVal(Nodo(fplist[i])) currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() #i+=2 #continue elif fplist[i] in ['<*', '<+']: #if fplist[i+1] == '*': currentTree = pStack.pop() #i+=2 #continue elif fplist[i] not in ['.', '|', '*>', '+', ')', '<*']: currentTree.setRootVal(Nodo(fplist[i])) parent = pStack.pop() currentTree = parent elif fplist[i] == ')': currentTree = pStack.pop() else: raise ValueError if currentTree.getLeftChild( ) is not None and currentTree.getRightChild() is not None: currentTree = pStack.pop() i += 1 #return eTree return currentTree
def buildParseTree(fpexp): ##code so you don't need to uses spaces to split the fpexp fplist = [] numberinstring = "" for token in fpexp: if (token not in ['(', '+', '-', '*', '/', ')']): numberinstring = numberinstring + token if token == "(": fplist.append(token) if token in ['(', '+', '-', '*', '/', ')']: if token == '*': fplist.append(token) if (numberinstring != ""): fplist.append(numberinstring) numberinstring = "" fplist.append(token) 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 = [] num = '' for ch in fpexp: if ch not in ['(', '+', '-', '*', '/', ')']: if num == '': num = ch else: num = num + ch else: if num != '': fplist.append(num) fplist.append(ch) num = '' 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 ['+', '-', '*', '/', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent else: raise ValueError return eTree
def buildParseTree_bool(fpexp): '''requires fully parenthesized expression ''' fpexp = fpexp.strip() 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 ['and', 'or']: currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == 'not': parent = pStack.pop() currentTree = parent currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() elif i not in ['and', 'not', 'or', ')', '(']: try: currentTree.setRootVal(i) parent = pStack.pop() currentTree = parent except ValueError: raise ValueError("token '{}' is not a valid Boolean".format(i)) return eTree