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)) parent = p_stack.pop() current_tree = parent 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 arrayBST(l, start, end): mid = (start + end) / 2 if start <= end: tree = BinaryTree(l[mid]) tree.left = arrayBST(l, start, mid - 1) tree.right = arrayBST(l, mid + 1, end) 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 not in ['and', 'or', 'not', ')']: #added boolean operators currentTree.setRootVal(int(i)) parent = pStack.pop() currentTree = parent elif i in ['and', 'or', 'not']: #added boolean operators 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(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 testTreeWithOneNode(): print(divider + "Executing testTreeWithOneNode()...") tree = BinaryTree() tree.insert(Node(0)) assert (tree.size == 1) assert (tree.height == 0) print("Passed" + divider)
def buildParseTree(the_exp): the_list = the_exp.split() p_stack = Stack() the_tree = BinaryTree('') p_stack.push(the_tree) current_tree = the_tree for i in the_list: if i == '(': current_tree.insertLeft('') p_stack.push(current_tree) current_tree = current_tree.getLeftChild() elif i not in ['+', '-', '*', '/', ')']: current_tree.setRootValue(int(i)) current_tree = p_stack.pop() elif i in ['+', '-', '*', '/']: current_tree.setRootValue(i) current_tree.insertRight('') p_stack.push(current_tree) current_tree = current_tree.getRightChild() elif i == ')': current_tree = p_stack.pop() else: raise ValueError return the_tree
def testEmptyTree(): print(divider + "Executing testEmptyTree()...") tree = BinaryTree() assert (tree.size == 0) assert (tree.height == 0) assert (tree.root is None) print("Passed" + divider)
def build_parse_tree(exp): tokens = exp # print(tokens) stack = Stack() tree = BinaryTree('?') stack.push(tree) currentTree = tree for t in tokens: # RULE 1: If token is '(' add a new node as left child # and descend into that node if t == '(': currentTree.insert_left('?') stack.push(currentTree) currentTree = currentTree.get_left_tree() # RULE 2: If token is operator set key of current node # to that operator and add a new node as right child # and descend into that node elif t in ['+', '-', '*', '/', '**']: currentTree.set_key(t) currentTree.insert_right('?') stack.push(currentTree) currentTree = currentTree.get_right_tree() # RULE 3: If token is number, set key of the current node # to that number and return to parent elif t not in ['+', '-', '*', '/', '**', ')'] : currentTree.set_key(float(t)) parent = stack.pop() currentTree = parent # RULE 4: If token is ')' go to parent of current node elif t == ')': currentTree = stack.pop() else: raise ValueError return tree
def testBFSSingleInsert(): print(divider + "Executing testBFSSingleInsert()...") nodes = [] tree = BinaryTree() tree.insert(Node(7)) nodes = tree.getNodesBFS() print(nodesToString(nodes)) assert (nodes[0].data == 7) print("Passed" + divider)
def testSingleInserts(loops): print(divider + "Executing testSingleInserts()...") for i in range(loops): tree = BinaryTree() val = randint(MIN_INT_32, MAX_INT_32) tree.insert(Node(val)) assert (tree.size == 1) assert (tree.height == 0) print("Passed" + divider)
def __init__(self, *args, **kwargs): #init method is inialized for each time that a test is run super(TestBinarySearchTree, self).__init__(*args, **kwargs) self.word = "hey" self.binaryTree = BinaryTree(self.word) self.words = [ "this", "is", "my", "exercise"] for word in self.words: self.binaryTree.insert_value(word)
def testSequentialInsert(): print(divider + "Executing testSequentialInsert()...") tree = BinaryTree() for i in range(1, 11): tree.insert(Node(i)) assert (tree.root.data == 1) assert (tree.size == 10) #print("Tree height is {}, expected to be {}".format(tree.height, 9)) assert (tree.height == 9) print("Passed" + divider)
def testBFSRandom(): print(divider + "Executing testBFSRandom()...") tree = BinaryTree() expectedNodes = [32, 16, 50, 2, 30, 48, 53, 5, 18, 12] for num in randomNumbers: tree.insert(Node(num)) bfsNodes = tree.getNodesBFS() print(nodesToString(bfsNodes)) # Ensure that the order of the nodes is in the proper order for BFS for i in range(0, len(expectedNodes)): assert (bfsNodes[i].data == expectedNodes[i]) print("Passed" + divider)
def testRandomInsert(): print(divider + "Executing testRandomInsert()...") numbers = [7, 2, 10, 4, 3, 1, 5, 8, 6, 9] tree = BinaryTree() for number in numbers: tree.insert(Node(number)) assert (tree.root.data == 7) assert (tree.size == 10) print("Tree height is {}, expected to be {}".format(tree.height, 4)) tree.printDFS() print() tree.printBFS() assert (tree.height == 4) print("Passed" + divider)
def testDFSRandom(): print(divider + "Executing testDFSRandom()...") tree = BinaryTree() expectedNodes = [32, 16, 2, 5, 12, 30, 18, 50, 48, 53] for number in randomNumbers: tree.insert(Node(number)) assert (tree.size == len(randomNumbers)) nodes = tree.getNodesDFS() print("Returned nodes = {}".format(nodesToString(nodes))) print("Expected nodes = {}".format([n for n in expectedNodes])) # Ensure that the order of the nodes is in the proper order for DFS for i in range(0, len(nodes)): assert (nodes[i].data == expectedNodes[i]) print("Passed" + divider)
def in_pre(inorder, preorder, start, end): if start > end: return None tree = BinaryTree(preorder[in_pre.index]) in_pre.index += 1 if start == end: return tree i = inorder.index(tree.key) tree.left = in_pre(inorder, preorder, start, i - 1) tree.right = in_pre(inorder, preorder, i + 1, end) return tree
def setUp(self): cathy = TreeNode('Cathy') cathy.left = TreeNode('Alex') cathy.right = TreeNode('Frank') sam = TreeNode('Sam') sam.left = TreeNode('Nancy') violet = TreeNode('Violet') violet.left = TreeNode('Tony') violet.right = TreeNode('Wendy') sam.right = violet les = TreeNode('Les') les.left = cathy les.right = sam self.tree = BinaryTree(les)
def sort(data_array, order="Desc"): heap_type = (order == "Desc" and "min") or "max" # 建立堆方式1 从最后一个节点父节点开始 start_index = BinaryHeap.get_parent_index(len(data_array) - 1) for adjust_index in range(start_index, -1, -1): BinaryHeap.__move__down(heap_type, data_array, adjust_index) # 建立堆方式2 每个节点都向上调整 # for i in range(len(input_data)): # BinaryHeap.__move__up__(heap_type, input_data, i) bt = BinaryTree(data_array) node_text_map, edges = bt.get_show_info() GraphVisualization.show(node_text_map, edges, view_graph=True) # 依次与第i个元素交换 然后调整 for i in range(len(data_array)-1, 0, -1): data_array[i], data_array[0] = data_array[0], data_array[i] BinaryHeap.__move__down(heap_type, data_array, 0, i) return data_array
def tree(self): chars = list(set(self.text)) occurs = {c: self.text.count(c)/len(self.text) for c in self.text} key = lambda i: occurs[i] chars = sorted(chars, key = key) nodes = [Node(label = c) for c in chars] while len(nodes) > 1: n1, n2 = nodes[0], nodes[1] del nodes[0] nodes[0] = Node(label = n1.label+n2.label, left_neigh = n1, right_neigh = n2) occurs[nodes[0].label] = occurs[n1.label] + occurs[n2.label] i = 0 while i < len(nodes) - 1 and occurs[nodes[i].label] >= occurs[nodes[i+1].label]: nodes[i], nodes[i+1] = nodes[i+1], nodes[i] i += 1 return BinaryTree(nodes[0], chars)
def build_parse_tree(fpexp): stack = Stack() node = BinaryTree(None) stack.push(node) current = node for s in fpexp.split(' '): if s == '(': current.insert_left(None) stack.push(current) current = current.get_left_child() elif s == ')': current = stack.pop() elif s in '+-*/': current.set_root_value(s) current.insert_right(None) stack.push(current) current = current.get_right_child() else: current.set_root_value(int(s)) current = stack.pop() return node
def insert(self, key, value): """Permette di inserire un valore all'interno del dizionario nella maniera corretta""" pair = [key, value] newt = BinaryTree(BinaryNode(pair)) if self.tree.root == None: self.tree.root = newt.root else: curr = self.tree.root #nodo corrente pred = None #nodo precedente che abbiamo analizzato while curr != None: pred = curr if key <= self.key(curr): #chiave che sto inserendo e' piu piccola di quella corrente curr = curr.leftSon else: curr = curr.rightSon if key <= self.key(pred): self.tree.insertAsLeftSubTree(pred, newt) else: self.tree.insertAsRightSubTree(pred, newt)
def testFind(): print(divider + "Executing testFind()...") tree = BinaryTree() lowerBound = 0 upperBound = 100 # Insert values for i in range(lowerBound, upperBound): tree.insert(Node(i)) # Ensure all inserted values are found for i in range(lowerBound, upperBound): assert (tree.find(i, tree.root)) # Ensure values outside of range are not found for i in range(-10000, lowerBound): assert (not tree.find(i, tree.root)) for i in range(upperBound, 10000): assert (not tree.find(i, tree.root)) print("Passed " + divider)
def buildParseTree(fpexp): #creates an empty list and then iterates through the expression #appending items into fpList #checks to see if the item in the expression is a number and if the index #before is a number to group them together and append together in list fpList = [""] for i in fpexp.replace(" ", ""): if i.isdigit() and fpList[-1].isdigit(): fpList[-1] = fpList[-1] + i else: fpList.append(i) fpList.pop(0) 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 insert(self, key, value): newt = BinaryTree(BinaryNode([ key, value, 0 ])) #Primo cambiamento e' tripletta al posto della coppia key value if self.tree.root == None: self.tree.root = newt.root else: curr = self.tree.root pred = None while curr != None: pred = curr if key <= self.key(curr): curr = curr.leftSon else: curr = curr.rightSon if key <= self.key(pred): self.tree.insertAsLeftSubTree(pred, newt) else: self.tree.insertAsRightSubTree(pred, newt) self.balInsert( newt.root ) #secondo cambiamento e' la chiamata del metodo per bilanciare l'albero
inorder(tree.right) return l def Symmetry(): equal = True sym = inorder(tree) length = len(sym) print sym, length while length > 1 and equal: first = sym.pop() last = sym.pop(0) length -= 2 if first == last: equal = True continue else: equal = False print equal tree = BinaryTree(3) tree.insert_left(9) tree.insert_right(20) tree.get_left_child().insert_left(4) tree.get_left_child().insert_right(5) tree.get_right_child().insert_left(15) tree.get_right_child().insert_right(7) Symmetry()
def __init__(self): self.tree = BinaryTree( ) #Node's info now is a triple [key,value,height]
from binaryTree import BinaryTree tree = BinaryTree(20) tree.insert_left(8) tree.insert_right(22) tree.get_left_child().insert_left(4) tree.get_left_child().insert_right(12) tree.get_left_child().get_right_child().insert_left(10) tree.get_left_child().get_right_child().insert_right(14) def lca_without_parent(root, value1, value2): while root != None: if root.key > value1 and root.key > value2: root = root.left elif root.key < value1 and root.key < value2: root = root.right else: return root.key print lca_without_parent(tree, 4, 14)
""" for each_element in some_list: if each_element not in sorted_list: return False for index in range(len(sorted_list) - 1): if sorted_list[index] > sorted_list[index + 1]: return False return True # -----------------------------------------------------------------------------| head_value = 15 head_node = Node(value = head_value) binary_tree = BinaryTree(head = head_node) my_random_list = [head_value] # trial insert for iteration in range(20000): random_number = random.randint(0, 2000) new_node = Node(value = random_number) binary_tree.insert(new_node = new_node) my_random_list.append(random_number) # print("List was", my_random_list) print("Sorting status: ", check_sort(my_random_list, binary_tree.sort())) print(len(binary_tree)) # slow method. use numpy
from binaryTree import BinaryTree tree = BinaryTree(26) tree.insert_left(10) tree.insert_right(3) tree.get_left_child().insert_left(6) tree.get_left_child().insert_right(4) tree.get_right_child().insert_right(3) def sum_nodes(root): if root==None: return 0 return sum_nodes(root.left) + root.key + sum_nodes(root.right) def sumtree(root): if root==None or (root.left==None and root.right==None): return 1 ls = sum_nodes(root.left) rs = sum_nodes(root.right) if (root.key == ls+rs) and (sumtree(root.left)) and (sumtree(root.right)): return 1 return 0 print sumtree(tree)
print("delete nodes with one child") bst.delete(16) bst.delete(12) bst.preorderTraversal() print("delete nodes with two children") bst.delete(14) bst.preorderTraversal() print("delete root") bst.delete(20) bst.preorderTraversal() print("Validate bst", bst.validateBST()) from binaryTree import BinaryTree r = BinaryTree(20) r.insertLeft(10) r.insertRight(30) r.leftChild.insertLeft(12) r.leftChild.insertRight(8) BinaryTree.validateBST = BinarySearchTree.validateBST print("Validate r", r.validateBST()) """ Tree ---> 20 10 30 8 14 25 32 12 16 13 18 """