def buildParseTree(fexp): fplist = fexp.split() pStack = Stack() eTree = BinaryTree('') pStack.push(eTree) currentTree = eTree for i in fplist: if i == '(': currentTree.setLeftChild(BinaryTree('')) 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(BinaryTree('')) pStack.push(currentTree) currentTree = currentTree.getRightChild() elif i == ')': currentTree = pStack.pop() else: raise ValueError print etree
def test_tree_case4(self): # 1 # 2 3 # 4 5 node4 = TreeNode(4) node2 = TreeNode(2, left=node4) node5 = TreeNode(5) node3 = TreeNode(3, right=node5) node1 = TreeNode(1, node2, node3) tree1 = BinaryTree(node1) assert tree1.root is node1 assert tree1.is_empty() is False assert tree1.size == 5 assert tree1.levels == 3 assert tree1.serialize() == '1,2,3,4,#,#,5' assert tree1.level_order() == [[1], [2, 3], [4, 5]] assert tree1.pre_order() == [1, 2, 4, 3, 5] assert tree1.in_order() == [4, 2, 1, 3, 5] assert tree1.post_order() == [4, 2, 5, 3, 1] tree2 = BinaryTree(serialize=tree1.serialize()) assert tree2.root.val == 1 assert tree2.is_empty() is False assert tree2.size == 5 assert tree2.levels == 3 assert tree2.serialize() == '1,2,3,4,#,#,5' assert tree2.level_order() == [[1], [2, 3], [4, 5]] assert tree2.pre_order() == [1, 2, 4, 3, 5] assert tree2.in_order() == [4, 2, 1, 3, 5] assert tree2.post_order() == [4, 2, 5, 3, 1] assert tree1 == tree2
def parse_expression(tokens): parentheses = {')': '(', ']': '[', '}': '{'} stack = ArrayStack() for token in tokens: try: token = BinaryTree(int(token)) except ValueError: pass if token not in parentheses: stack.push(token) else: try: arg_2 = stack.pop() operator = stack.pop() arg_1 = stack.pop() opening_group_symbol = stack.pop() if parentheses[token] != opening_group_symbol: return parse_tree = BinaryTree(operator) parse_tree.left_node = arg_1 parse_tree.right_node = arg_2 stack.push(parse_tree) except EmptyStackError: return if stack.is_empty(): return parse_tree = stack.pop() if not stack.is_empty(): return return parse_tree
def create_expression_tree(self): """ Cria uma arvore binaria a partir da expressao posfixa """ if len(self.postfix_expression) == 1: self.expression_tree = BinaryTree(self.postfix_expression[0]) return stack = [] for value in self.postfix_expression: if value in '.+': right = stack.pop() left = stack.pop() bin_tree = BinaryTree(value) bin_tree.set_left_child(left) bin_tree.set_right_child(right) stack.append(bin_tree) elif value == '*': right = stack.pop() bin_tree = BinaryTree(value) bin_tree.set_right_child(right) stack.append(bin_tree) else: stack.append(value) self.expression_tree = stack[0] self.expression_tree.print_treeview()
def test_is_strict(self): tree = BinaryTree() assert tree.is_strict() is True tree = BinaryTree(serialize='1') assert tree.is_strict() is True tree = BinaryTree(serialize='1,2,#') assert tree.is_strict() is False tree = BinaryTree(serialize='1,#,2') assert tree.is_strict() is False tree = BinaryTree(serialize='1,2,3') assert tree.is_strict() is True tree = BinaryTree(serialize='1,2,3,4,5,6,#') assert tree.is_strict() is False tree = BinaryTree(serialize='1,2,3,4,5,6,7') assert tree.is_strict() is True tree = BinaryTree(serialize='1,2,3,#,#,6,7') assert tree.is_strict() is True tree = BinaryTree(serialize='1,2,3,#,#,#,7') assert tree.is_strict() is False tree = BinaryTree(serialize='1,#,3,#,#,6,7') assert tree.is_strict() is False
def test_tree_case5(self): # 1 # 2 3 # 4 5 # 6 7 node6 = TreeNode(6) node4 = TreeNode(4, right=node6) node7 = TreeNode(7) node5 = TreeNode(5, left=node7) node2 = TreeNode(2, left=node4) node3 = TreeNode(3, right=node5) node1 = TreeNode(1, node2, node3) tree1 = BinaryTree(node1) assert tree1.root is node1 assert tree1.is_empty() is False assert tree1.size == 7 assert tree1.levels == 4 assert tree1.serialize() == '1,2,3,4,#,#,5,#,6,#,#,#,#,7,#' assert tree1.level_order() == [[1], [2, 3], [4, 5], [6, 7]] assert tree1.pre_order() == [1, 2, 4, 6, 3, 5, 7] assert tree1.in_order() == [4, 6, 2, 1, 3, 7, 5] assert tree1.post_order() == [6, 4, 2, 7, 5, 3, 1] tree2 = BinaryTree(serialize=tree1.serialize()) assert tree2.root.val is 1 assert tree2.is_empty() is False assert tree2.size == 7 assert tree2.levels == 4 assert tree2.serialize() == '1,2,3,4,#,#,5,#,6,#,#,#,#,7,#' assert tree2.level_order() == [[1], [2, 3], [4, 5], [6, 7]] assert tree2.pre_order() == [1, 2, 4, 6, 3, 5, 7] assert tree2.in_order() == [4, 6, 2, 1, 3, 7, 5] assert tree2.post_order() == [6, 4, 2, 7, 5, 3, 1] assert tree1 == tree2
def test_tree_case3(self): # 1 # 2 # 3 node3 = TreeNode(3) node2 = TreeNode(2, right=node3) node1 = TreeNode(1, right=node2) tree1 = BinaryTree(node1) assert tree1.root is node1 assert tree1.is_empty() is False assert tree1.size == 3 assert tree1.levels == 3 assert tree1.serialize() == '1,#,2,#,#,#,3' assert tree1.level_order() == [[1], [2], [3]] assert tree1.pre_order() == [1, 2, 3] assert tree1.in_order() == [1, 2, 3] assert tree1.post_order() == [3, 2, 1] tree2 = BinaryTree(serialize=tree1.serialize()) assert tree2.root.val == 1 assert tree2.is_empty() is False assert tree2.size == 3 assert tree2.levels == 3 assert tree2.serialize() == '1,#,2,#,#,#,3' assert tree2.level_order() == [[1], [2], [3]] assert tree2.pre_order() == [1, 2, 3] assert tree2.in_order() == [1, 2, 3] assert tree2.post_order() == [3, 2, 1] assert tree1 == tree2
def parse_expression(tokens): stack = ArrayStack() for token in tokens: stack.push(token) if token in [')', '}', ']']: try: right = stack.pop() arg_2 = stack.pop() if type(arg_2) == str: arg_2 = BinaryTree(int(arg_2)) operate = stack.pop() arg_1 = stack.pop() if type(arg_1) == str: arg_1 = BinaryTree(int(arg_1)) left = stack.pop() except EmptyStackError: return except ValueError: return if (left, right) not in [('(', ')'), ('{', '}'), ('[', ']')]: return parse_tree = BinaryTree(operate) parse_tree.left_node = arg_1 parse_tree.right_node = arg_2 stack.push(parse_tree) if stack.is_empty(): return parse_tree = stack.pop() if not stack.is_empty(): return if type(parse_tree) == str: parse_tree = BinaryTree(int(parse_tree)) return parse_tree
def setUp(self): self.empty_tree = BinaryTree() self.tree = BinaryTree() self.tree.insert(3) self.tree.insert(4) self.tree.insert(2) self.tree.insert(1) self.tree.insert(20) self.tree.insert(5)
def test_bst_is_valid(): # test on a valid bst input bst = BinaryTree([5, 2, 7, 1, 9]) assert bst_is_valid(bst) is True # test on an invalid bst bst.root.data = 10 assert bst_is_valid(bst) is False # test on an empty tree, should be valid bst = BinaryTree([]) assert bst_is_valid(bst) is True
def test_max_distance(self): tree = BinaryTree() with pytest.raises(EmptyError): tree.max_distance() tree = BinaryTree(serialize='1') assert tree.max_distance() == 0 tree = BinaryTree(serialize='1,2,#') assert tree.max_distance() == 1 tree = BinaryTree(serialize='1,#,2') assert tree.max_distance() == 1 tree = BinaryTree(serialize='1,2,#,3,#,#,#') assert tree.max_distance() == 2 tree = BinaryTree(serialize='1,#,2,#,#,#,3') assert tree.max_distance() == 2 tree = BinaryTree(serialize='1,2,3,4,#,#,5') assert tree.max_distance() == 4 tree = BinaryTree(serialize='1,2,3,4,#,#,5') assert tree.max_distance() == 4 tree = BinaryTree(serialize='1,2,3,4,#,#,#') assert tree.max_distance() == 3
def buildDecisionTree(sofar, todo): """ @return: decision tree root which contains all references to other nodes """ if len(todo) == 0: return BinaryTree(sofar) else: withElement = buildDecisionTree(sofar + [todo[0]], todo[1:]) withoutElement = buildDecisionTree(sofar, todo[1:]) here = BinaryTree(sofar) here.set_left_branch(withElement) here.set_right_branch(withoutElement) return here
def test_empty_tree(self): tree = BinaryTree() assert tree.root is None assert tree.is_empty() is True assert tree.size == 0 assert tree.levels == 0 assert tree.__repr__() == "BinaryTree(serialize='')" assert tree.serialize() == '' assert tree.level_order() == [] assert tree.pre_order() == [] assert tree.in_order() == [] assert tree.post_order() == [] assert tree == BinaryTree()
def test_binary_tree(): """ The function tests if the binary tree is working properly. """ # build the binary tree root_node = Node(3) binary_tree = BinaryTree(root_node) binary_tree.insert(Node(2)) binary_tree.insert(Node(5)) binary_tree.insert(Node(1)) # replace temporary with none binary_tree.insert(Node('Temporary')) binary_tree.insert(Node(4)) binary_tree.insert(Node(6)) # replace temporary with none binary_tree._left_child._right_child = None # right tree to the lowest node 6 binary_tree._right_child._right_child._right_child = BinaryTree(Node(7)) # traverse binary tree print('Traverse Preorder-----------------') binary_tree.traverse('preorder') print() print('Traverse Inorder-----------------') binary_tree.traverse('inorder') print() print('Traverse Postorder-----------------') binary_tree.traverse('postorder') print() # use explanation (not code) from https://www.geeksforgeeks.org/find-maximum-or-minimum-in-binary-tree/ to build # maximum method print(f'maximum node value: {binary_tree.maximum()}') # height function operates well only in this specific situations print( f'height of binary tree: {BinaryTree.height(binary_tree)} levels (includes level 0 -> levels 0-3)' ) print(f'size of binary tree: {BinaryTree.size(binary_tree)} nodes') print( f'if node with value 5 is found in binary tree: {binary_tree.search(5)}' )
def test_is_bst(self): bt = BinaryTree(10) leaf = bt.add_left(7) bt.add_right(11, leaf) bt.add_right(39) self.assertFalse(bt.is_bst()) bt = BinaryTree(10) leaf = bt.add_left(7) bt.add_right(8, leaf) bt.add_right(39) self.assertTrue(bt.is_bst())
def test_is_bst(self): tree = BinaryTree() assert tree.is_bst() is True tree = BinaryTree(serialize='1') assert tree.is_bst() is True tree = BinaryTree(serialize='1,2,3,4,#,#,5,#,6,#,#,#,#,7,#') assert tree.is_bst() is False tree = BinaryTree(serialize='2,1,3') assert tree.is_bst() is True tree = BinaryTree(serialize='10,1,20,#,5,15,#') assert tree.is_bst() is True
def test_is_hyperbalanced(): t = BinaryTree([1, 2, 4, 5, 3]) assert is_hyperbalanced(t) is False t = BinaryTree([ 5, 3, 7, 1, 4, 6, 9, ]) assert is_hyperbalanced(t) is True t = BinaryTree() assert is_hyperbalanced(t) is True print('Is hyperbalanced passes the tests.')
def test_find_node(self): bt = BinaryTree() bt.root = Node(4) bt.root.left_child = Node(2) bt.root.right_child = Node(6) bt.root.left_child.right_child = Node(3) bt.root.right_child.left_child = Node(5) bt.root.right_child.right_child = Node(8) bt.root.right_child.right_child.left_child = Node(7) bt.root.right_child.right_child.right_child = Node(12) # test 1 found_node, previous_node = bt.find_node(bt.root, None, 4) self.assertEqual(bt.root, found_node) self.assertEqual(None, previous_node) # test 2 found_node, previous_node = bt.find_node(bt.root, None, 2) self.assertEqual(bt.root.left_child, found_node) self.assertEqual(bt.root, previous_node) # test 3 found_node, previous_node = bt.find_node(bt.root, None, 12) self.assertEqual(bt.root.right_child.right_child.right_child, found_node) self.assertEqual(bt.root.right_child.right_child, previous_node) # test 4: found_node, previous_node = bt.find_node(bt.root, None, 999) self.assertEqual(None, found_node) self.assertEqual(None, previous_node)
def test_binary_tree_add_root_node(self): bt = BinaryTree() bt.add_node(4) self.assertEqual(4, bt.root.value) self.assertEqual(1, bt.count) self.assertEqual(None, bt.root.left_child) self.assertEqual(None, bt.root.right_child)
def test_delete_node_remove_node_with_right_child_that_has_a_left_child_and_left_grandchildren( self): bt = BinaryTree() bt.root = Node(4) bt.root.left_child = Node(2) bt.root.right_child = Node(15) bt.root.left_child.left_child = Node(1) bt.root.left_child.right_child = Node(3) bt.root.right_child.left_child = Node(5) bt.root.right_child.right_child = Node(25) bt.root.right_child.right_child.left_child = Node(19) bt.root.right_child.right_child.left_child.right_child = Node(20) bt.root.right_child.right_child.left_child.left_child = Node(18) bt.root.right_child.right_child.left_child.left_child.left_child = Node( 17) bt.count = 11 bt.delete_node(15) self.assertEqual(4, bt.root.value) self.assertEqual(17, bt.root.right_child.value) self.assertEqual(5, bt.root.right_child.left_child.value) self.assertEqual(25, bt.root.right_child.right_child.value) self.assertEqual(19, bt.root.right_child.right_child.left_child.value) self.assertEqual( 18, bt.root.right_child.right_child.left_child.left_child.value) self.assertEqual( 20, bt.root.right_child.right_child.left_child.right_child.value) self.assertEqual( None, bt.root.right_child.right_child.left_child.left_child.left_child) self.assertEqual(2, bt.root.left_child.value) self.assertEqual(1, bt.root.left_child.left_child.value) self.assertEqual(3, bt.root.left_child.right_child.value) self.assertEqual(10, bt.count)
def test_binary_tree(N): t = BinaryTree() for i in range(int(N / 2)): t.append_left(i) for i in range(int(N / 2)): t.append_right(int(N / 2) + i) print_tree(t.root)
def buildParseTree(fpexp): node = BinaryTree(None) parents = Stack() for c in fpexp.split(): if c == '(': # (: create left -> push current node to stack -> descending to left node.insertLeft(None) parents.push(node) node = node.getLeft() elif c == ')': # ): pop node from stack -> ascending to root if parents.isEmpty() is False: node = parents.pop() elif c in ['+', '-', '*', '/']: # operator: set value -> create right -> push current node to stack -> descending to right node.setRoot(c) node.insertRight(None) parents.push(node) node = node.getRight() else: # operand: number, set value -> pop node from stack -> ascending to root try: node.setRoot(int(c)) node = parents.pop() except ValueError: raise ValueError( "token '{}' is not a valid integer. ".format(c)) return node
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 convert_ptb_to_tree(line): index = 0 tree = None line = line.rstrip() stack = [] parts = line.split() for p_i, p in enumerate(parts): try: # opening of a bracket, create a new node, take parent from top of stack if p == '(': if tree is None: tree = BinaryTree(index) else: add_descendant(tree, index, stack[-1]) # add the newly created node to the stack and increment the index stack.append(index) index += 1 # close of a bracket, pop node on top of the stack elif p == ')': stack.pop(-1) # otherwise, create a new node, take parent from top of stack, and set word else: add_descendant(tree, index, stack[-1]) tree.set_word(index, p) index += 1 except: continue return tree
def test_lca(self): tree = BinaryTree("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L") first_node = tree.find_node("K") second_node = tree.find_node("I") lca = tree.lowest_common_ancestor(first_node, second_node) self.assertEqual(lca.key, "B")
def insertInBinaryTreeUsingLevelOrder(root, data): newNode = BinaryTree(data) if root is None: root = newNode return root q = Queue() q.enqueue(root) node = None while not q.isEmpty(): node = q.dequeue() # dequeue FIFO if data == node.get_data(): return root # basically level order, insert would be where there is no left if node.left is not None: q.enqueue(node.left) else: node.left = newNode return root # if left all filled, insert right if node.right is not None: q.enqueue(node.right) else: node.right = newNode return root
def test_determine_node_to_add_to_larger_value_one_right_child_exists( self): bt = BinaryTree() bt.root = Node(4) bt.root.right_child = Node(8) node_to_add_to = bt._determine_node_to_add_to(bt.root, 5) self.assertEqual(bt.root.right_child, node_to_add_to)
def build_pars_tree(fp_exp): fp_list = conv_list(fp_exp) p_stack = Stack() e_tree = BinaryTree("") p_stack.push(e_tree) current_tree = e_tree step = 0 for i in fp_list: step = step + 1 if i == "(": current_tree.insert_left("") p_stack.push(current_tree) current_tree = current_tree.get_left_child() elif i in "+-*/": current_tree.set_root_value(i) current_tree.insert_right('') p_stack.push(current_tree) current_tree = current_tree.get_right_child() elif i == ")": current_tree = p_stack.pop() elif i not in "()+*-/": current_tree.set_root_value(int(i)) parent = p_stack.pop() current_tree = parent else: raise Exception("ValueError") return e_tree
def test_remove_1_right_child(self): tree = BinaryTree() node1 = Node((5, None)) node2 = Node((3, None)) node3 = Node((4, None)) tree.insert(node1) tree.insert(node2) tree.insert(node3) self.assertEqual(tree.root, node1) self.assertEqual(node1.left_node, node2) self.assertEqual(node1.right_node, None) self.assertEqual(node2.parent, node1) self.assertEqual(node2.left_node, None) self.assertEqual(node2.right_node, node3) self.assertEqual(node3.parent, node2) self.assertEqual(node3.left_node, None) self.assertEqual(node3.right_node, None) self.assertEqual(tree.order(), [node2, node3, node1]) tree.remove(node2) self.assertEqual(tree.root, node1) self.assertEqual(node1.left_node, node3) self.assertEqual(node1.right_node, None) self.assertEqual(node3.parent, node1) self.assertEqual(node3.left_node, None) self.assertEqual(node3.right_node, None) self.assertEqual(tree.order(), [node3, node1])
def ParseTree(expr): # Implement parse tree my_list = expr.split() stack = Stack() tree = BinaryTree('') stack.push(tree) current_tree = tree for i in my_list: if i == '(': current_tree.insert_left('') stack.push(current_tree) current_tree = current_tree.get_left_child() elif i in ['+', '-', '*', '/']: current_tree.set_root_value(i) current_tree.insert_right('') stack.push(current_tree) current_tree = current_tree.get_right_child() elif i == ')': current_tree = stack.pop() else: try: current_tree.set_root_value(int(i)) parent = stack.pop() current_tree = parent except ValueError: raise ValueError("token '{}' is not a valid integer".format(i)) return tree