def main(): # initialize a binary search tree bst1 = BST() bst1.insert(7) bst1.insert(3) bst1.insert(8) bst1.insert(5) bst1.insert(2) bst1.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 bst2 = BST() bst2.insert(3) bst2.insert(2) bst2.insert(5) # the tree is like # 3 # / \ # 2 5 bst3 = BST() bst3.insert(3) bst3.insert(1) bst3.insert(9) print "is tree2 a subtree of tree1? ", isSubtree(bst1.root, bst2.root) print "is tree3 a subtree of tree1? ", isSubtree(bst1.root, bst3.root)
def __init__(self, fileName): self.tokens = [] self.pif = [] self.st = BST() self.fileName = fileName self.pifout = open("pif.txt", 'w') self.stout = open("st.txt", 'w')
def main(): nums = [ 10, 50, 100, 500, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500, 5000 ] generate_tree(nums) for opt in range(3): if opt == 0: T = BST() elif opt == 1: T = AVL() elif opt == 2: T = BTree() file_name = '../test/' + T.__class__.__name__ + '.pkl' if os.path.exists(file_name): continue res = [] for n in nums: tree = extract_tree_element(n) for v in tree: T.insert(v) cnt = 0 for v in tree: cnt += T.search(v) avg = cnt / n res.append(avg) with open(file_name, 'wb') as f: pickle.dump(res, f) f.close() plot()
def full_binary_tree(): test_tree = BST() test_tree.insert(5) test_tree.insert(8) test_tree.insert(9) test_tree.insert(2) test_tree.insert(4) return test_tree
def populate(n): myList = [] myBST = BST() while len(myList) != n: randNum = (random.randrange(0, n + 1)) myList.append(randNum) myBST.append(randNum) return (myList, myBST)
def makeTree(self): self.tree = BST.BST(7) root = self.tree.root self.tree.insert(4) self.tree.insert(1) self.tree.insert(5) self.tree.insert(8) self.tree.insert(7.5)
def populate(n): randomList = [] bstList = BST() for i in range(0, n): randomList.append(random.randint(0, n)) bstList.append(random.randint(0, n)) return (randomList, bstList)
def __init__(self, Numbers, Canvas): #初始化Do_BSTree类 Numbers.sort() self.The_BST = BST.BST(Numbers[0]) self.The_BST.Arrange_Numbers(Numbers) self.The_BST.root = self.The_BST.Create_BST() self.The_Canvas = Canvas self.The_Lines = [] self.The_Ovals = [] self.The_Texts = []
def buildAllBST(self): allBST = [] # liste de tous les arbres for att in self.data[0].keys(): # Pour chaque argument, on crée un arbre a = BST() for dico in self.data: # Pour chacun des Dictionnaires, on ajoute l'argument 'att' dans l'arbre node = Node(dico[att], self.data.index(dico)) a.addNode(node) allBST.append(a) return allBST
def showMenu(): mytree = BST() answer = 0 contacto1 = Contact("Maria", 0) contacto2 = Contact("Pedro", -2) contacto3 = Contact("Juan", -3) contacto4 = Contact("Carlos", -1) contacto5 = Contact("Jose", 2) contacto6 = Contact("Jazmin", 1) contacto7 = Contact("Daniel", 3) mytree.add(contacto1) mytree.add(contacto2) mytree.add(contacto3) mytree.add(contacto4) mytree.add(contacto5) mytree.add(contacto6) mytree.add(contacto7) ''' mytree.searchContact(0) mytree.remove(123) mytree.remove(0) mytree.searchContact(0) mytree.searchContact(3) ''' while (answer != 4): print("\n-------MENU-------") print( "1. Añadir Contacto\n2. Buscar Contacto\n3. Eliminar Contacto\n4. Salir\n" ) answer = int(input("Escoge una opcion\n")) if (answer == 1): name = input("\nAgregar nombre del contacto que desea agregar\n") number = int(input("\nAgregar numero del usuario\n")) newContact = Contact(name, number) mytree.add(newContact) elif (answer == 2): number = int( input("\nAgregar numero del usario para hacer la busqueda\n")) mytree.searchContact(number) elif (answer == 3): number = int( input("\nAgregar numero del usario que desea eliminar\n")) mytree.remove(number) elif (answer == 4): pass else: print("\nOpcion no disponible\n")
def constructTree2(): tree = BST() tree.insert(4) tree.insert(1) tree.insert(7) tree.insert(6) tree.insert(5) tree.insert(2) tree.insert(3) return tree
def populate(n): randomList = [] bst = BST() for i in range(0, n): randomInt = random.randint(0, n) randomList.append(randomInt) bst.append(randomInt) return [randomList, bst]
def test_add_node_int(self): int_bst = BST() int_bst.add_node(1) int_bst.add_node(2) int_bst.add_node(3) self.assertEqual(1, int_bst.find_node(1).key) self.assertEqual(2, int_bst.find_node(2).key) self.assertEqual(3, int_bst.find_node(3).key) self.assertIsNone(int_bst.find_node(4))
def test_add_node_string(self): string_bst = BST() string_bst.add_node("string a") string_bst.add_node("string b") string_bst.add_node("string c") string_bst.add_node("string c") # adding repeat value self.assertEqual("string a", string_bst.find_node("string a").key) self.assertEqual("string b", string_bst.find_node("string b").key) self.assertEqual("string b", string_bst.find_node("string b").key) self.assertIsNone(string_bst.find_node("string d"))
def main(): mytree = BST() mytree.insert(3) mytree.insert(5) mytree.insert(2) mytree.insert(7) mytree.insert(12) mytree.insert(8) print "Is the tree balanced? ", IsBalancedTree(mytree)
def test_runs(self): """basics test runs.""" t = BST() t.insert(5) t.insert(4) t.insert(3) t.insert(7) t.insert(6) self.assertFalse(t.contains(9)) self.assertEqual(t.find_max(), 7) self.assertEqual(t.find_min(), 3)
def main(): # initialize a binary search tree bst = BST() bst.insert(3) bst.insert(5) bst.insert(2) bst.insert(7) bst.insert(12) bst.insert(8) print isBST1(bst.root) print isBST2(bst.root)
def test_find_node(self): int_bst = BST() # testing trying to find a node when no nodes are on BST self.assertIsNone(int_bst.find_node(1)) # adding the node of int 1 to the tree, then attempting to find this node int_bst.add_node(1) int_bst.add_node(5) int_bst.add_node(3) self.assertEqual(1, int_bst.find_node(1).key) self.assertEqual(5, int_bst.find_node(5).key) self.assertEqual(3, int_bst.find_node(3).key) self.assertIsNone(int_bst.find_node(2)) self.assertIsNone(int_bst.find_node(4))
def populate(n): if (isinstance(n, int)): if (n < 0): raise Exception('n has to be a positive integer') else: newList = [] newBST = BST() for i in range(0, n): randInt = random.randint(0, n) newList.append(randInt) newBST.append(randInt) return (newList, newBST) else: raise Exception('n has to be an integer')
def bstAlg(): bst = BST() for i in range(20): bst.insert(BSTNode(nodeValues[i], bst.nil, bst.nil, bst.nil)) print() for i in range(20, 100): bst.insert(BSTNode(nodeValues[i], bst.nil, bst.nil, bst.nil)) print("These keys in inorder are: ") bst.inorder() print() print("\nNow do 200 searches. ") for i in range(200): n = searchValues[i] if bst.search(n) == bst.nil: print(n, " not found") else: print(n, " found") print("\nNow search for & delete some nodes.") for i in range(2000): z = bst.search(deleteValues[i]) if z != bst.nil: bst.delete(z) print("The keys in the trees in order are now: ") bst.inorder() print() print( "\nNow print the keys in order again by calling minimum, then repeatedly calling successor." ) x = bst.minimum() print(x, end=' ') x = x.successor(bst.nil) while x != bst.nil: print(x, end=' ') x = x.successor(bst.nil) print() print("\nThe maximum key is: ") print(bst.maximum()) print("\nThe final tree looks like this.") print() bst.print() print()
def main(): # initialize a binary search tree bst1 = BST() bst1.insert(7) bst1.insert(3) bst1.insert(8) bst1.insert(5) bst1.insert(2) bst1.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 findPath(bst1.root, 8)
def balance_bst(bst): # validation check if bst == None: print("Tree doesn't contain any nodes") return # local variables bst_inorder = get_bst_inorder(bst.root) new_tree = BST.BST() # helper function that will recursively split the "bst_inorder" list by 2 # and append the middle value of each of the half list to the newly created tree def build_balanced_tree(root, start_idx, end_idx): # base case to have the recursion bottom out. # 1. Ensure the start_idx is always less than the end_idx # 2. If indices are the same, then this is the last # element that needs to be inserted in to the tree if start_idx > end_idx: return if start_idx == end_idx: insert_node(new_tree, bst_inorder[start_idx]) else: # compute the midpoint of the current list and use that value to build the tree mid_point = (start_idx + end_idx) // 2 # append the current mid value insert_node(new_tree, bst_inorder[mid_point]) # recursively work on the left half of the list build_balanced_tree(new_tree, start_idx, mid_point - 1) # do the same for the right side of the list build_balanced_tree(new_tree, mid_point + 1, end_idx) # call the helper function to get the fun started build_balanced_tree(new_tree, 0, len(bst_inorder) - 1) # return the new tree return new_tree
def main(): # initialize a binary search tree bst = BST() bst.insert(7) bst.insert(3) bst.insert(8) bst.insert(5) bst.insert(2) bst.insert(12) # the tree is like # 7 # / \ # 3 8 # / \ / # 2 5 12 print "LCA of 2 and 12 is: ", findLCA(2, 12, bst.root).value print "LCA of 2 and 5 is: ", findLCA(2, 5, bst.root).value
def test_find_lca(self): our_tree = BST() input_values = [15, 14, 28, 22, 9, 12, 30, 29, 4, 7, 13] for x in input_values: our_tree.add_node(x) # LCA of 12 4 is 9 self.assertEqual(9, our_tree.find_lca(12, 4), "test") # LCA of 7 4 is 4 self.assertEqual(4, our_tree.find_lca(7, 4)) # LCA of 14 22 is 15 self.assertEqual(15, our_tree.find_lca(14, 22)) # LCA of 15 4 is 15 self.assertEqual(15, our_tree.find_lca(15, 4)) # LCA of 30 29 is 30 self.assertEqual(30, our_tree.find_lca(30, 29)) # LCA of 7 13 is 9 self.assertEqual(9, our_tree.find_lca(7, 13)) # LCA of 30 99 (99 not on tree) is 30 self.assertEqual(30, our_tree.find_lca(30, 99))
import BST # Set up tree tree = BST(4) # Insert elements tree.insert(2) tree.insert(1) tree.insert(3) tree.insert(5) # Check search # Should be True print tree.search(4) # Should be False print tree.search(6)
from BST import * # BST will look like this: https://i.ibb.co/1dQdqDD/Untitled.png our_tree = BST() input_values = [15, 14, 28, 22, 9, 12, 30, 29, 4, 7, 13] for x in input_values: our_tree.add_node(x) print("LCA of 12 4:", our_tree.find_lca(12, 4)) print("LCA of 7 4: ", our_tree.find_lca(7, 4)) print("LCA of 14 22: ", our_tree.find_lca(14, 22)) print("LCA of 15 4: ", our_tree.find_lca(15, 4)) print("LCA of 30 29: ", our_tree.find_lca(30, 29)) print("LCA of 7 13: ", our_tree.find_lca(7, 13)) print("on tree 7 ", our_tree.find_node(7) is not None) print("on tree 99 ", our_tree.find_node(99) is not None)
import BST tree = BST.BST(10) tree.insert(5, tree.root) tree.insert(15, tree.root) tree.insert(25, tree.root) tree.insert(12, tree.root) tree.insert(35, tree.root) tree2 = BST.BST(10) tree2.insert(5, tree2.root) tree2.insert(15, tree2.root) tree2.insert(25, tree2.root) tree2.insert(12, tree2.root) tree2.insert(35, tree2.root) print(tree.is_identical(tree2.root))
print("Tree structure after inverting: ") print(BST.root.__repr__()) print() def test_height_function(BST): print("Computing the height of the tree") tree_height = BST_Lib.get_tree_height(BST) print("Tree has height of : " + str(tree_height)) ############################################# Main ############################################## # Create tree BST_Tree = BST.BST() # Test Append Function test_insert_function(BST_Tree) # Test Print Functions #test_print_functions(BST_Tree) # Test the balancing function #test_balancing_function(BST_Tree) # Test min/max FUnction #test_min_max_function(BST_Tree) # Test invert tree function # test_invert_function(BST_Tree)
screen.blit(text, textpos) #recursively draw left and right child of current node. drawNode(node.left, y + 1, lx) drawNode(node.right, y + 1, rx) node = bst.root size = width, height = (getnodewidth(node) + 1) * tilesize, (getnodeheight(node) + 1) * tilesize screen = pygame.display.set_mode(size) screen.fill(white) drawNode(node, 1, getnodewidth(node.left) + 1) pygame.display.flip() bst = BST.BST() bst.put("E", 1) bst.put("A", 2) bst.put("C", 3) bst.put("S", 4) bst.put("I", 5) bst.put("H", 6) bst.put("Q", 7) bst.put("N", 8) bst.put("R", 9) bst.put("X", 10) while True: for event in pygame.event.get(): if event.type == pygame.QUIT: sys.exit() drawBST(bst)
def buildBST(self, att): a = BST() for dico in self.data: node = Node(dico[att], self.data.index(dico)) a.addNode(node) return a