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 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 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_insert(self): var = globalVar() #Contains variables for tree insertion bTree = BinaryTree() bTree.insert(value= var.p1) self.assertEqual(bTree._root.value, var.p1) bTree.insert(value=var.p2) self.assertEqual(bTree.findRightMost(bTree._root).value, var.p2) bTree.insert(value=var.p5) self.assertEqual(bTree.findLeftMost(bTree._root).value, var.p5 )
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 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 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 constructBinaryTree(self, btree: BinaryTree): """Construct the binary tree based on user input. :param btree: Binary tree on which new nodes to be added :type btree: BinaryTree """ while True: data = input("Enter Node Data (Numeric), others if you are done:") if data.isdigit(): btree.addToTree(int(data)) else: return
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
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 __init__(self, fileName): self.tree = BinaryTree() with open(fileName) as f: flag = False lastWord = '' preLastWord = '' oneWordLineWord = '' for line in f: words = re.split(r'\W+|\d+|_+', line) words = list(filter(bool, words)) if len(words) == 0: continue if oneWordLineWord != '': words.insert(0, oneWordLineWord) oneWordLineWord = '' if len(words) == 1: oneWordLineWord = words[0].lower() continue if flag: #pre last first node = self.tree.find( NodeWithData.makeKey(preLastWord, lastWord)) if node == None: node = NodeWithData(preLastWord, lastWord) self.tree.add(node) node.UpdateDict(preLastWord, lastWord, words[0].lower()) #last first second node = self.tree.find( NodeWithData.makeKey(lastWord, words[0].lower())) if node == None: node = NodeWithData(lastWord, words[0].lower()) self.tree.add(node) node.UpdateDict(lastWord, words[0].lower(), words[1].lower()) else: flag = True lastWord = words[-1].lower() preLastWord = words[-2].lower() for i in range(len(words) - 2): w1 = words[i].lower() w2 = words[i + 1].lower() node = self.tree.find(NodeWithData.makeKey(w1, w2)) if node == None: node = NodeWithData(w1, w2) self.tree.add(node) node.UpdateDict(w1, w2, words[i + 2].lower()) if oneWordLineWord + preLastWord + lastWord != '': node = self.tree.find( NodeWithData.makeKey(preLastWord, lastWord)) if node == None: node = NodeWithData(preLastWord, lastWord) self.tree.add(node) node.UpdateDict(preLastWord, lastWord, oneWordLineWord)
class EmptyTests(unittest.TestCase): def setUp(self): self.tree = Tree(None) def test_empty_size(self): self.assertEqual(self.tree.size(), 0) def test_depth_empty(self): self.assertEqual(self.tree.depth(), 0) def test_empty_balance(self): self.assertEqual(self.tree.balance(), 0)
def test_find(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) bTree.insert(value= var.p5) bTree.insert(value= var.p4) self.assertEqual(bTree.find(var.p1).value, var.p1) self.assertEqual(bTree.find(var.p4).value, var.p4)
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 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 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 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 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 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 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 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_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 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 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 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 second_min(tree: BinaryTree): root = tree.root height = tree.find_height(root) second_min = math.inf q = [] q.append(root) h = 0 while h < height: u = q.pop(0) if u.left != None: q.append(u.right) q.append(u.left) if u.value > root.value and u.value < second_min: second_min = u.value h += 1 if second_min > root.value and second_min != math.inf: return second_min else: return -1
def buildMPLogicParseTree(s): """ To build the logic Parse tree, getting each element for it. """ fplist = s.split() pStack = Stack() leTree = BinaryTree('') pStack.push(leTree) currentTree = leTree for j in fplist: if j == '(': currentTree.insertLeft('') pStack.push(currentTree) currentTree = currentTree.getLeftChild() elif j in ['AND', 'OR']: currentTree.setRootVal(j) currentTree.insertRight('') pStack.push(currentTree) currentTree = currentTree.getRightChild() elif j in ['T', 'F']: currentTree.setRootVal(j) parent = pStack.pop() currentTree = parent elif j[0] == 'M' or j[0] == 'P': currentTree.setRootVal(j[0]) currentTree.insertLeft(j[2:]) parent = pStack.pop() currentTree = parent elif j == ')': currentTree = pStack.pop() else: print("token '{}' is not a valid expression".format(j)) return None return leTree
def build_parse_tree2(fpexp): fplist = fpexp.split() eTree = BinaryTree('') currentTree = eTree for i in fplist: if i == '(': currentTree.insert_left('') currentTree = currentTree.get_left() elif i not in ['+', '-', '*', '/', ')']: currentTree.set_root(int(i)) currentTree = currentTree.get_parent() elif i in ['+', '-', '*', '/']: currentTree.set_root(i) currentTree.insert_right('') currentTree = currentTree.get_right() elif i == ')': currentTree = currentTree.get_parent() else: raise ValueError return eTree
def buildParseTree(fpexp): #remove any white spaces fpexp = fpexp.replace(' ', '') #replace left parenthesis with space after fpexp = fpexp.replace('(', '( ') #replace right parenthesis with space before fpexp = fpexp.replace(')', ' )') #replace operators with spaces before and after fpexp = fpexp.replace('+', ' + ') fpexp = fpexp.replace('-', ' - ') fpexp = fpexp.replace('*', ' * ') fpexp = fpexp.replace('/', ' / ') fplist = fpexp.split() print("String before processing: {}".format(fplist)) 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 __init__(self): BinaryTree.__init__(self) self.Node = self.TreapNode self._twist_cw = utils._twist_cw self._twist_ccw = utils._twist_ccw
""" File: testbinarytree.py Builds a full binary tree with 7 nodes. """ from binarytree import BinaryTree # Create initial leaf nodes a = BinaryTree("A") b = BinaryTree("B") c = BinaryTree("C") d = BinaryTree("D") e = BinaryTree("E") f = BinaryTree("F") g = BinaryTree("G") # Build the tree from the bottom up, where # d is the root node of the entire tree # Build and set the left subtree of d b.setLeft(a) b.setRight(c) d.setLeft(b) # Build and set the right subtree of d f.setLeft(e) f.setRight(g) d.setRight(f)
class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot(): return tree.getRoot() elif target < tree.getRoot(): return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) 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 inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" # Exercise pass def postorder(self): """Returns a list containing the results of a postorder traversal.""" # Exercise pass def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" # Exercise pass def remove(self, item): # Exercise pass
class BinaryTreeTests(unittest.TestCase): def setUp(self): self.tree = Tree(7) def test_insert(self): self.tree.insert(9) self.assertTrue(self.tree.contains(9)) def test_reinsert(self): self.tree.insert(7) self.assertEqual(self.tree.size(), 1) def test_contains_false(self): self.assertFalse(self.tree.contains(6)) def test_size(self): self.assertEqual(self.tree.size(), 1) self.tree.insert(6) self.assertEqual(self.tree.size(), 2) def test_depth(self): self.tree.insert(8) self.tree.insert(9) self.tree.insert(10) self.tree.insert(5) self.assertEqual(self.tree.depth(), 4) def test_balance_pos(self): self.tree.insert(10) self.tree.insert(8) self.tree.insert(9) self.assertEqual(self.tree.balance(), 3) def test_balance_neg(self): self.tree.insert(1) self.tree.insert(2) self.tree.insert(9) self.assertEqual(self.tree.balance(), -1) def test_balance_even(self): self.tree.insert(10) self.tree.insert(4) self.assertEqual(self.tree.balance(), 0)
def setUp(self): self.tree = Tree(None)
def setUp(self): self.tree = Tree(7)
class BST(object): def __init__(self): self._tree = BinaryTree.THE_EMPTY_TREE self._size = 0 def isEmpty(self): return len(self) == 0 def __len__(self): return self._size def __str__(self): return str(self._tree) def __iter__(self): return iter(self.inorder()) def find(self, target): """Returns data if target is found or None otherwise.""" def findHelper(tree): if tree.isEmpty(): return None elif target == tree.getRoot(): return tree.getRoot() elif target < tree.getRoot(): return findHelper(tree.getLeft()) else: return findHelper(tree.getRight()) return findHelper(self._tree) 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 remove(self, item): """Removes and returns item from the tree.""" # Helper function to adjust placement of an item def liftMaxInLeftSubtreeToTop(top): # Replace top's datum with the maximum datum in the left subtree # Pre: top has a left child # Post: the maximum node in top's left subtree # has been removed # Post: top.getRoot() = maximum value in top's left subtree parent = top currentNode = top.getLeft() while not currentNode.getRight().isEmpty(): parent = currentNode currentNode = currentNode.getRight() top.setRoot(currentNode.getRoot()) if parent == top: top.setLeft(currentNode.getLeft()) else: parent.setRight(currentNode.getLeft()) # Begin main part of the method if self.isEmpty(): return None # Attempt to locate the node containing the item itemRemoved = None preRoot = BinaryTree(None) preRoot.setLeft(self._tree) parent = preRoot direction = 'L' currentNode = self._tree while not currentNode.isEmpty(): if currentNode.getRoot() == item: itemRemoved = currentNode.getRoot() break parent = currentNode if currentNode.getRoot() > item: direction = 'L' currentNode = currentNode.getLeft() else: direction = 'R' currentNode = currentNode.getRight() # Return None if the item is absent if itemRemoved == None: return None # The item is present, so remove its node # Case 1: The node has a left and a right child # Replace the node's value with the maximum value in the # left subtree # Delete the maximium node in the left subtree if not currentNode.getLeft().isEmpty() \ and not currentNode.getRight().isEmpty(): liftMaxInLeftSubtreeToTop(currentNode) else: # Case 2: The node has no left child if currentNode.getLeft().isEmpty(): newChild = currentNode.getRight() # Case 3: The node has no right child else: newChild = currentNode.getLeft() # Case 2 & 3: Tie the parent to the new child if direction == 'L': parent.setLeft(newChild) else: parent.setRight(newChild) # All cases: Reset the root (if it hasn't changed no harm done) # Decrement the collection's size counter # Return the item self._tree = preRoot.getLeft() self._size -= 1 return itemRemoved # Traversal methods def inorder(self): """Returns a list containing the results of an inorder traversal.""" lyst = [] self._tree.inorder(lyst) return lyst def preorder(self): """Returns a list containing the results of a preorder traversal.""" lyst = [] self._tree.preorder(lyst) return lyst def postorder(self): """Returns a list containing the results of a postorder traversal.""" lyst = [] self._tree.postorder(lyst) return lyst def levelorder(self): """Returns a list containing the results of a levelorder traversal.""" lyst = [] self._tree.levelorder(lyst) return lyst
def remove(self, item): """Removes and returns item from the tree.""" # Helper function to adjust placement of an item def liftMaxInLeftSubtreeToTop(top): # Replace top's datum with the maximum datum in the left subtree # Pre: top has a left child # Post: the maximum node in top's left subtree # has been removed # Post: top.getRoot() = maximum value in top's left subtree parent = top currentNode = top.getLeft() while not currentNode.getRight().isEmpty(): parent = currentNode currentNode = currentNode.getRight() top.setRoot(currentNode.getRoot()) if parent == top: top.setLeft(currentNode.getLeft()) else: parent.setRight(currentNode.getLeft()) # Begin main part of the method if self.isEmpty(): return None # Attempt to locate the node containing the item itemRemoved = None preRoot = BinaryTree(None) preRoot.setLeft(self._tree) parent = preRoot direction = 'L' currentNode = self._tree while not currentNode.isEmpty(): if currentNode.getRoot() == item: itemRemoved = currentNode.getRoot() break parent = currentNode if currentNode.getRoot() > item: direction = 'L' currentNode = currentNode.getLeft() else: direction = 'R' currentNode = currentNode.getRight() # Return None if the item is absent if itemRemoved == None: return None # The item is present, so remove its node # Case 1: The node has a left and a right child # Replace the node's value with the maximum value in the # left subtree # Delete the maximium node in the left subtree if not currentNode.getLeft().isEmpty() \ and not currentNode.getRight().isEmpty(): liftMaxInLeftSubtreeToTop(currentNode) else: # Case 2: The node has no left child if currentNode.getLeft().isEmpty(): newChild = currentNode.getRight() # Case 3: The node has no right child else: newChild = currentNode.getLeft() # Case 2 & 3: Tie the parent to the new child if direction == 'L': parent.setLeft(newChild) else: parent.setRight(newChild) # All cases: Reset the root (if it hasn't changed no harm done) # Decrement the collection's size counter # Return the item self._tree = preRoot.getLeft() self._size -= 1 return itemRemoved
def __init__(self): BinaryTree.__init__(self)
else: return [node] + TracePath(node.getParent()) def find6(node): return node.getValue() == 6 def find10(node): return node.getValue() == 10 def find2(node): return node.getValue() == 2 def findq(node): return node.getValue() == "q" # Test n5 = BinaryTree(5) n2 = BinaryTree(2) n1 = BinaryTree(1) n4 = BinaryTree(4) n8 = BinaryTree(8) n6 = BinaryTree(6) n7 = BinaryTree(7) n3 = BinaryTree(3) n5.setLeftBranch(n2) n2.setParent(n5) n5.setRightBranch(n8) n8.setParent(n5) n2.setLeftBranch(n1) n1.setParent(n2) n2.setRightBranch(n4)
return [node] else: return [node] + TracePath(node.getParent()) def find6(node): return node.getValue() == 6 def find10(node): return node.getValue() == 10 def find2(node): return node.getValue() == 2 #Test # Test n5 = BinaryTree(5) n2 = BinaryTree(2) n1 = BinaryTree(1) n4 = BinaryTree(4) n8 = BinaryTree(8) n6 = BinaryTree(6) n7 = BinaryTree(7) n3 = BinaryTree(3) n5.setLeftBranch(n2) n2.setParent(n5) n5.setRightBranch(n8) n8.setParent(n5) n2.setLeftBranch(n1) n1.setParent(n2) n2.setRightBranch(n4)
def __init__(self,key): BinaryTree.__init__(self, key) self.isBlack = True