def build_parse_tree(exp): lst = exp.split() s = Stack() a_tree = BinaryTree('') # ? s.push(a_tree) cur = a_tree for i in lst: if i == '(': cur.insert_left(BinaryTree('')) s.push(cur) cur = cur.get_left_child() elif i not in '+-*/)': cur.set_root_val(i) parent = s.pop() cur = parent elif i in '+-*/': cur.set_root_val(i) cur.insert_right(BinaryTree('')) s.push(cur) cur = cur.get_right_child() elif i == ')': parent = s.pop() cur = parent else: return ValueError return a_tree
def fillTree(node): childID = str(node) parentTuple = getParents(childID) if (parentTuple == ('','')): return node else: node.setLeft(fillTree(BinaryTree(parentTuple[0])))#Mother node.setRight(fillTree(BinaryTree(parentTuple[1])))#Father return node
def test_root(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) bTree.insert(value= var.p2) bTree.insert(value= var.p3) self.assertEqual(bTree._root.value, var.p1) bTree2 = BinaryTree() bTree2.insert(value= var.p4) bTree2.insert(value= var.p5) self.assertEqual(bTree2._root.value, var.p4)
def testSumWithinRange(): leftTree = BinaryTree(3) leftTree.addLeftChild(2) leftTree.addRightChild(4) rightTree = BinaryTree(8) rightTree.addLeftChild(6) rightTree.addRightChild(10) tree = BinaryTree(5) tree.setLeftChild(leftTree) tree.setRightChild(rightTree) assert sumWithinRange(tree, [4, 9]) == 23
def lineageListToTree(lineageList): #escape case for recursion if(len(lineageList[0]) == 1): return BinaryTree(lineageList[0][0]) root = BinaryTree(lineageList[0][0]) lineageList[0] = lineageList[0][1:] #root = BinaryTree(('z2qI',5)) current = root stack = [BinaryTree(("Sentinel Node",-1)), root] for row in lineageList: for cell in row: previous = current current = BinaryTree(cell) # fills in right node (father) first if(previous.getRight() == BinaryTree.THE_EMPTY_TREE): #print(str(current.getRoot()) + str(previous.getRoot())) if(current.getRoot()[1] < previous.getRoot()[1]): stack.append(previous) previous.setRight(current) else: previous.setLeft(current) #recursive way to continue beyond one lineage page # runs at the end of every row # if the current node's id string starts with the deceased placeholder string, then do not go to the lineage page if (current.getRoot()[0][:deceasedDragonPlaceholderStringLen] != deceasedDragonPlaceholderString): #count up number of nodes to get back to the root child node = current columnCounter = 1 while (node.getParent() != BinaryTree.THE_EMPTY_TREE): columnCounter += 1 node = node.getParent() #if the number of nodes to get back to the root child = 12, then the lineage could go on #past the end of the lineage page and that dragon's lineage page must be loaded as well if (columnCounter == 12): tempLineageList = idToLineageList(current.getRoot()[0]) tempNode = lineageListToTree(tempLineageList) if (previous.getRight() == current): previous.setRight(tempNode) elif(previous.getLeft() == current): previous.setLeft(tempNode) current = stack.pop() return root
def buildtree(exp): parents = Stack() tree = BinaryTree(None) current = tree curnum = '' for index in range(len(exp)): # print parents if exp[index] == '(': current.addLeft(None) parents.push(current) current = current.getLeft() nextnum = False elif exp[index] in operator: current.setRootVal(exp[index]) parents.push(current) current.addRight(None) current = current.getRight() nextnum = False elif exp[index] == ')': if parents.isEmpty(): return current else: current = parents.pop() nextnum = False elif exp[index].isdigit(): curnum = curnum + exp[index] if not exp[index + 1].isdigit(): current.setRootVal(curnum) current = parents.pop() curnum = '' else: raise ValueError('Contains unknown expression') return current
def build_parse_tree(fpexp): fplist = fpexp.split() pStack = [] eTree = BinaryTree('') pStack.append(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.insert_left('') pStack.append(currentTree) currentTree = currentTree.get_left() elif i not in ['+', '-', '*', '/', ')']: currentTree.set_root(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/']: currentTree.set_root(i) currentTree.insert_right('') pStack.append(currentTree) currentTree = currentTree.get_right() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
def add(self, newItem): """Adds newItem to the tree.""" # Helper function to search for item's position def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem < currentItem: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right) # End of addHelper # Tree is empty, so new item goes at the root if self.isEmpty(): self._tree = BinaryTree(newItem) # Otherwise, search for the item's spot else: addHelper(self._tree) self._size += 1
def buildParseTree(fpexp): print(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 build_parse_tree(fp_exp): fp_list = fp_exp.split() p_stack = Stack() e_tree = BinaryTree('') p_stack.push(e_tree) current_tree = e_tree for i in fp_list: if i == '(': current_tree.insert_left('') p_stack.push(current_tree) current_tree = current_tree.get_left_child() elif i not in ['+', '-', '*', '/', ')']: current_tree.set_root_val(int(i)) current_tree = p_stack.pop() elif i in ['+', '-', '*', '/']: current_tree.set_root_val(i) current_tree.insert_right('') p_stack.push(current_tree) current_tree = current_tree.get_right_child() elif i == ')': current_tree = p_stack.pop() else: raise ValueError return e_tree
def test_not_accepting_duplicates(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) self.assertTrue(bTree.insert(value= var.p2)) with self.assertRaises(Exception): #Insert for second time, expect an exception bTree.insert(value= var.p1)
def coefficientOfRelationship(id1,id2): if( not idExists(id1)): return (id1 + " does not exist") if( not idExists(id2)): return (id2 + " does not exist") if (id1 == id2): return 1 print("writing lineage list1") lineageList = idToLineageList(id1) print("filling tree1 from list") tree1 = lineageListToTree(lineageList) cleanUpTupleTree(tree1) print("writing lineage list2") lineageList = idToLineageList(id2) print("filling tree2 from list") tree2 = lineageListToTree(lineageList) cleanUpTupleTree(tree2) hypotheticalChild = BinaryTree("Hypothetical Child") hypotheticalChild.setLeft(tree1) hypotheticalChild.setRight(tree2) return 2 * COI(hypotheticalChild)
def binaryparsertree(expr): exp = expr.split() pStack = [] eTree = BinaryTree('') pStack.append(eTree) currentTree = eTree for i in exp: if i == '(': currentTree.addLeft('') pStack.append(currentTree) currentTree = currentTree.getLeftChild() elif i not in ['+', '-', '/', '*', ')']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '/', '*']: currentTree.setRootVal(i) currentTree.addRight('') pStack.append(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError return eTree
def buildParseTree(fpexp): # fplist = [ch for ch in fpexp if ch != " "] 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': currentTree = pStack.pop() currentTree.leftChild = None currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i not in ['+', '-', '*', '/', ')', 'and', 'or']: currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['+', '-', '*', '/', 'or', 'and']: 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) currentTree = pStack.pop() elif i in "+-*/": currentTree.setRootVal(i) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ")": currentTree = pStack.pop() else: raise ValueError("Unknown Operator: " + i) return eTree
def buildMPLogicParseTree(exp): """ params: ------ exp: (str) return type: (BinaryTree) "Builds a parse tree from an MP logic expression" """ elist = exp.split() #split th expression on spaces into a list pStack = Stack() # Instanciate Stack Object bTree = BinaryTree('') #instanciate BinaryTree object pStack.push(bTree) #add the BinaryTree object into the Stack Object current_tree = bTree #copy BinaryTree object into another variable for i in elist: #loop through the list of expression items if i == '(': # check if the current element is an opening bracket current_tree.insertLeft( '' ) #inserts a blank to the left child of the BinaryTree object. pStack.push( current_tree) #add the BinaryTree object into the Stack Object current_tree = current_tree.getLeftChild( ) #change the root pointer of the BinaryTree object # to its left child elif i in [ 'OR', 'AND' ]: #check if current item in the list expression is an OR or AND current_tree.setRootVal( i) #sets root value of the BinaryTree object to i current_tree.insertRight( '' ) #inserts a blank to the right child of the BinaryTree object. pStack.push( current_tree) #add the BinaryTree object into the Stack Object current_tree = current_tree.getRightChild( ) #change the root pointer of the BinaryTree object # to its right child elif i.startswith('M') or i.startswith('P') or i in [ 'T', 'F' ]: #check if current item in the list expression starts with P or M or is an OR or AND current_tree.setRootVal( i) #sets root value of the BinaryTree object to i parent = pStack.pop( ) #removes the recently added item to the stack and assigns it to parent current_tree = parent # assigns parent to current_tree elif i == ')': #checks if current item in the expression list is a closing bracket current_tree = pStack.pop( ) #removes the recently added item to the stack and assigns it to current_tree else: print("Invalid expression") #gives feedback incase of an error return None return bTree #return BinaryTree object
def main(): tree = BinaryTree() tree.set('c', 'C') tree.set('h', 'H') tree.set('a', 'A') tree.set('e', 'E') tree.set('f', 'F') tree.set('d', 'D') tree.set('b', 'B') tree.set('k', 'K') tree.set('j', 'J') tree.set('i', 'I') tree.set('g', 'G') tree.set('l', 'L') print('Lookups:') print(tree.get('f')) print(tree.get('b')) print(tree.get('i')) print() print('DFS preorder:') for key, value in tree.walk_dfs_preorder(): print(key, value) print() print('DFS inorder:') for key, value in tree.walk_dfs_inorder(): print(key, value) print() print('DFS postorder:') for key, value in tree.walk_dfs_postorder(): print(key, value) print() print('BFS:') for key, value in tree.walk_bfs(): print(key, value) print() print('Initial tree:') print(tree) print() print('Remove b:') tree.remove('b') print(tree) print() print('Remove f:') tree.remove('f') print(tree) print() print('Remove h:') tree.remove('h') print(tree) print()
def test(): bt = BinaryTree(1) bt.insertLeft(2) bt.insertLeft(3) assert bt.left.key == 3 assert bt.left.left.key == 2 print("assertions ok")
def test_findMin(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) bTree.insert(value= var.p2) self.assertEqual(bTree.findMin().value, var.p1) bTree.insert(value= var.p5) self.assertEqual(bTree.findMin().value, var.p5)
def testBuildMPLogicParseTree(self): """ Test if pt is of type BinaryTree""" pt = buildMPLogicParseTree( '( ( T AND F ) OR M_0.3 )') #build an MPLogic parse tree expected = BinaryTree("") #Define the expected value self.assertEqual( type(pt), type(expected) ) #compares to make sure that our code evaluates to the expected value
def test_binarytree(): test_passed = True test_database = pickle.load( open( 'testdatabase.p', 'rb' ) ) test_database = test_database['binarytree'] keys = test_database['keys'] result = test_database['result'] BT = BinaryTree() for key in keys: BT.insert(key,None) nodes = [] nodes.append(BT._root) nodes_checked = 0 while len(nodes) > 0: node = nodes.pop() if not node is None: nodes_checked += 1 nodes.append(node._left) nodes.append(node._right) target = result[node._key] if node._left is None: if not target['l'] is None: test_passed = False else: if not node._left._key == target['l']: test_passed = False if node._right is None: if not target['r'] is None: test_passed = False else: if not node._right._key == target['r']: test_passed = False BT = BinaryTree() BT.insert('1','a') BT.insert('1','b') BT.insert('1','c') if len(BT.get('1')) != 3: test_passed = False return test_passed
def test_findRightMost(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) bTree.insert(value= var.p2) self.assertEqual(bTree.findRightMost(bTree._root).value, var.p2) bTree.insert(value= var.p5) bTree.insert(value= var.p4) self.assertEqual(bTree.findRightMost(bTree._root).value, var.p4)
def main(): leftTree = BinaryTree(3) leftTree.addLeftChild(2) leftTree.addRightChild(4) rightTree = BinaryTree(8) rightTree.addLeftChild(6) rightTree.addRightChild(10) tree = BinaryTree(5) tree.setLeftChild(leftTree) tree.setRightChild(rightTree) print("Binary tree\n--------------------------------\n") pprint(vars(tree)) rng = [4, 9] result = sumWithinRange(tree, rng) print(f"Sum of elements in range {rng} --> {result}")
def addHelper(tree): currentItem = tree.getRoot() left = tree.getLeft() right = tree.getRight() # New item is less, go left until spot is found if newItem < currentItem: if left.isEmpty(): tree.setLeft(BinaryTree(newItem)) else: addHelper(left) # New item is greater or equal, # go right until spot is found elif right.isEmpty(): tree.setRight(BinaryTree(newItem)) else: addHelper(right)
def buidTree(ino, pro): t = BinaryTree() index = Index() index.value = 0 start = 0 end = len(ino) - 1 root = _buildTree(ino, pro, start, end, index) t.root = root return t
def test_delete(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) bTree.insert(value= var.p2) bTree.insert(value= var.p3) self.assertEqual(bTree.find(var.p3).value, var.p3) bTree.delete(var.p3) with self.assertRaises(Exception): bTree.find(var.p3).value#Looking for deleted element
def buildTreeInPo(ino, poo): index = Index() length = len(ino) start = 0 end = length - 1 index.value = end root = _buildTreeInPo(ino, poo, start, end, index) t = BinaryTree() t.root = root return t
def test_findLeftMost(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) bTree.insert(value= var.p2) bTree.insert(value= var.p5) bTree.insert(value= var.p4) self.assertEqual(bTree.findLeftMost(bTree._root).value, var.p5) #The smallest value, ('AASE') bTree.insert(value= var.p6) bTree.insert(value= var.p3) self.assertEqual(bTree.findLeftMost(bTree._root).value, var.p6)
def test_BinaryTree(): r = BinaryTree('a') assert r.get_root_val() == 'a' assert r.get_left_child() is None r.insert_left('b') assert str(r.get_left_child()) == 'BinaryTree object: val=b' assert r.get_left_child().get_root_val() == 'b' r.insert_right('c') assert str(r.get_right_child()) == 'BinaryTree object: val=c' assert r.get_right_child().get_root_val() == 'c' r.get_right_child().set_root_val('hello') assert r.get_right_child().get_root_val() == 'hello'
def parse_tree(tree_input): bst = BinaryTree() input_datas = [] for item in tree_input: if item == 'N': input_datas.append(None) else: input_datas.append(int(item)) bst.create_bst(input_datas) return bst