def test_tree_generation(): for invalid_height in ['foo', -1, None]: with pytest.raises(InvalidTreeHeightError) as err: tree(height=invalid_height) assert str(err.value) == 'The height must be an integer between 0 - 9' root = tree(height=0) root.validate() assert root.height == 0 assert root.left is None assert root.right is None assert isinstance(root.value, int) for _ in range(REPETITIONS): random_height = random.randint(1, 9) root = tree(random_height) root.validate() assert root.height == random_height for _ in range(REPETITIONS): random_height = random.randint(1, 9) root = tree(random_height, is_perfect=True) root.validate() assert root.height == random_height assert root.is_perfect is True assert root.is_balanced is True assert root.is_strict is True
def buildData(values=None, height=None, perfect=False): if values: btTree = bt.build(values) elif height: btTree = bt.tree(height=height, is_perfect=perfect) else: btTree = None def convert(btTree): if not btTree: return None values = btTree.values nodes = [BinTreeNode(values.pop(0))] root = nodes[0] while len(values) > 0: parent = nodes.pop(0) left = BinTreeNode(values.pop(0)) right = BinTreeNode(values.pop(0) if len(values) > 0 else None) nodes.append(left) nodes.append(right) if parent and parent.val is not None: if left.val is not None: parent.left = left if right.val is not None: parent.right = right return root return (btTree, convert(btTree))
def test_max_leaf_depth(self): for _ in range(1000): h = randint(0, 9) t = tree(height=h) # print(t.height) print(t) self.assertEqual(t.max_leaf_depth, max_leaf_depth(t))
def test_tree_is_complete(self): for _ in range(1000): h = randint(0, 9) t = tree(height=h) print(t.is_complete) print(t) self.assertEqual(t.is_complete, tree_is_complete(t))
def test_print(): def convert_print(target): print(convert(target)) def convert_pprint(target): pprint(convert(target)) for invalid_argument in [1, 'foo']: with pytest.raises(ValueError) as err: pprint(invalid_argument) assert str(err.value) == 'Expecting a list or a node' for print_func in [pprint, convert_pprint]: with CaptureOutput() as output: print_func([]) assert output == [''] for print_func in [convert_print, pprint, convert_pprint]: with CaptureOutput() as output: print_func([1, 2]) assert output == ['', ' 1', ' / ', '2 ', ' '] with CaptureOutput() as output: print_func([1, None, 3]) assert output == ['', '1 ', ' \\ ', ' 3', ' '] with CaptureOutput() as output: print_func([1, 2, 3]) assert output == ['', ' 1 ', ' / \\ ', '2 3', ' '] with CaptureOutput() as output: print_func([1, 2, 3, None, 5]) assert output == [ '', ' __1 ', ' / \\ ', '2 3', ' \\ ', ' 5 ', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, None, 5, 6]) assert output == [ '', ' __1__ ', ' / \\ ', '2 3', ' \\ / ', ' 5 6 ', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, None, 5, 6, 7]) assert output == [ '', ' __1__ ', ' / \\ ', '2 3 ', ' \\ / \\ ', ' 5 6 7', ' ' ] with CaptureOutput() as output: print_func([1, 2, 3, 8, 5, 6, 7]) assert output == [ '', ' __1__ ', ' / \\ ', ' 2 3 ', ' / \\ / \\ ', '8 5 6 7', ' ' ] for _ in range(repetitions): bt = tree(height=10) with CaptureOutput() as output1: print(bt) assert output1 == str(bt).splitlines() assert output1 == stringify(bt).splitlines()
def main(): tr = tree() print('-----------------------------------------------------') print('tr {}:'.format(len(tr))) print(tr) res = print_tree(tr) # print('{} {}'.format(sum(len(i) for i in res), res)) pprint(res)
def test_binary_tree_values(self): for _ in range(20000): t = tree() # print(t) bt = binary_tree(t.values) # print(bt) self.assertEqual(t.values, binary_tree_values(bt))
def test_height(self): for _ in range(1000): h = randint(0, 9) t = tree(height=h) # print(t.height) # print(t) self.assertEqual(t.height, tree_height(t)) self.assertEqual(t.height, tree_height_iterative(t))
def test_tree(): for invalid_height in ['foo', -1]: with pytest.raises(ValueError) as err: tree(height=invalid_height) assert str(err.value) == 'Height must be a non-negative integer' for _ in range(repetitions): root = tree(height=0) assert attr(root, 'left') is None assert attr(root, 'right') is None assert isinstance(attr(root, 'value'), int) assert inspect(root)['height'] == 0 assert inspect(root)['is_height_balanced'] is True assert inspect(root)['is_weight_balanced'] is True for _ in range(repetitions): height = randint(1, 10) root = tree(height) nodes_to_visit = [root] while nodes_to_visit: node = nodes_to_visit.pop() assert isinstance(node, Node) assert isinstance(attr(node, 'value'), int) if attr(node, 'left') is not None: nodes_to_visit.append(attr(node, 'left')) if attr(node, 'right') is not None: nodes_to_visit.append(attr(node, 'right')) assert inspect(root)['height'] == height for _ in range(repetitions): height = randint(1, 10) root = tree(height, balanced=True) nodes_to_visit = [root] while nodes_to_visit: node = nodes_to_visit.pop() assert isinstance(node, Node) assert isinstance(attr(node, 'value'), int) if attr(node, 'left') is not None: nodes_to_visit.append(attr(node, 'left')) if attr(node, 'right') is not None: nodes_to_visit.append(attr(node, 'right')) assert inspect(root)['height'] == height assert inspect(root)['is_height_balanced'] is True assert inspect(root)['is_weight_balanced'] is True
def test_stress(): for _ in range(100): my_tree = tree(height=2, is_perfect=False) n = my_tree.size tree_reformat = convert_tree_format(my_tree) solver = Solver(n, tree_reformat) solver2 = Solver2(n, tree_reformat) if solver.is_bst() != solver2.is_bst(): print('n: ', n) print('tree_reformat: ', tree_reformat)
def post_tree(): """Method to create a random Binarytree object using POST""" new_tree = tree() list_rep = new_tree.values new_tree_obj = Binarytree() new_tree_obj.tree_list = list_rep new_tree_obj.save() key = 'Binarytree.' + new_tree_obj.id return jsonify(storage.all("Binarytree").get(key).to_dict())
def test_binary_tree(self): for _ in range(10000): t = tree() # Generate a random binary tree and return its root node # print(t) bt = binary_tree(t.values) self.assertEqual([e.val for e in t.preorder], preorder_array(bt)) self.assertEqual([e.val for e in t.preorder], preorder_array_iterative(bt)) self.assertEqual([e.val for e in t.inorder], inorder_array(bt)) self.assertEqual([e.val for e in t.inorder], inorder_array_iterative(bt)) self.assertEqual([e.val for e in t.postorder], postorder_array(bt)) self.assertEqual([e.val for e in t.postorder], postorder_array_iterative(bt)) self.assertEqual([e.val for e in t.levelorder], level_order_array(bt)) self.assertEqual([e.val for e in t.levelorder], level_order_array_recursive(bt))
def run_algo(iter_num): for i in range(iter_num): test_tree = tree(height=random.randint(0, 4), is_perfect=False) testTreeIsBalanced = isBalanced(test_tree) if testTreeIsBalanced != test_tree.is_balanced: print(test_tree) print('Tree is' + ('' if test_tree.is_balanced else ' not') + ' balanced. Manual algo returns {0}'.format( testTreeIsBalanced)) print('Max,min = {0}, {1}'.format(getMaxHeight(test_tree), getMinHeight(test_tree))) global PRINT PRINT = True isBalanced(test_tree) return
def test_very_big_tree(self): # test binary tree of height 9 root = tree(height=9) result = lca.find_lca(root, root.right.right.right.right, root.right.right.right.right.right.right.right) expected = root.right.right.right.right self.assertEqual(expected, result) result2 = lca.find_lca(root, root.left.left.right.left, root.left.left.left.right.right) expected2 = root.left.left self.assertEqual(expected2, result2)
class Node: __left=None __right=None __val=None def __init__(self, key): self.left = None self.right = None self.val = key # A utility function to insert a new node with the given key struct tree() tree.left = None tree.right =None k=None l=None __root = None
def build_code_tree(coder, tree_height=-1): """ Notes: On the diagram 8 is equal to 0 because of tree.value has to be int number. Args: coder: tree_height: Returns: """ if tree_height == -1: tree_height = coder.code_len code_tree = tree(height=tree_height, is_perfect=True) # set value for root code_tree.value = 18 state_dict = dict() state_dict[0] = coder.get_register_state() for ind, node in enumerate(code_tree.levelorder): left_son_ind = 2 * ind + 1 right_son_ind = 2 * ind + 2 if left_son_ind < len(code_tree.levelorder): # encode for the left son node.left.value = format_encoded_value_for_tree( coder.encode(input_sequence=np.array([1]), reset_register_state=True, register_state=state_dict[ind])) state_dict[left_son_ind] = coder.get_register_state() # encode for the right son node.right.value = format_encoded_value_for_tree( coder.encode(input_sequence=np.array([0]), reset_register_state=True, register_state=state_dict[ind])) state_dict[right_son_ind] = coder.get_register_state() return code_tree
def enc (x,t,min,max,n ): r=math.log(2,n) p=2**r if (x==t.x): k = Crypto.Random.random.randint(0, 1) else: k=None if (x>t.x or k==1): if (t.right!= None): return enc(x,t,max,min) elif (max-t.x<2): return rebalance (x,-1,n) t.right =HMAC.new(x,t.l,max-t.l/2,digestmod=SHA256) return t.right.l if (x<t.l or k==0): if (t.left!= None): return enc(x,t.left,min,t.l) elif (t.l-min<2): return rebalance(x,-1,p) t.left=tree(x,min+(t.l-min/2))
""" if root == None: return [] q = Queue.Queue() q.put(root) mainList = [] while(not q.empty()): level_num = q.qsize() # print "level_num =", level_num, sublist = [] for i in xrange(level_num): node_out = q.get() # print "i =", i, " | node_out.value =", node_out.value, " | queue = ", list(q.queue), if node_out.left != None: q.put(node_out.left) if node_out.right != None: q.put(node_out.right) sublist.append(node_out.value) # print " | subList: ", sublist mainList.append(sublist) return mainList # Generate a random binary tree and return its root node my_tree = tree(height=2, is_perfect=True) print(my_tree) print(binaryTreeLevelOrder(my_tree))
def main(): from binarytree import tree, bst, heap # https://pypi.org/project/binarytree/ root = tree(height=3) print(root) print(findAllRights(root))
from binarytree import tree, bst, heap, pprint my_tree = tree(height=2, balanced=True) def get_predicessor(root, val, predicessor): if root == None: return None if val > root.value: return get_predicessor(root.left, val, predicessor) if root.value == val: if root.right != None: predicessor[0] = get_min_node(root.value) return predicessor[0] else: predicessor[0] = root.value return get_predicessor(root.right, val, predicessor) def get_min_node(root): current = root while current.left: current = current.left return current.value pprint(my_tree) print get_predicessor(my_tree, 2, [1])
if root is not None: # if encounter a leaf if root.left is None and root.right is None: if root.value == sum: return(True) else: return(False) else: left_result = self.hasPathSum(root.left, sum - root.value) right_result = self.hasPathSum(root.right, sum - root.value) return(left_result or right_result) # if the root is None, # OR try to evaluate left and right nodes of a leaf else: return(False) random.seed(5) tree1 = binarytree.tree(height = 3, is_perfect = False) print(tree1) test = Solution() print(test.hasPathSum(tree1, 12)) print(test.hasPathSum(tree1, 36)) print(test.hasPathSum(tree1, 50)) print(test.hasPathSum(None, 50)) print(test.hasPathSum(tree1, -3))
for x in range(COMMON_SEQUENCE_N): E_SEQUENCE = E_SEQUENCE - int(N_SEQUENCE * PARTICIPATION_FREQ) else: print( 'Common sequence number to high for that frequency/total number of sequence.' ) sys.exit() ################################################################## dataset = [] for x in range(E_SEQUENCE): seq_range = random.randint(MIN_RANGE_SEQ_LENGTH, MAX_RANGE_SEQ_LENGTH) seq = [] for y in range(seq_range): tree_height = random.randint(MIN_RANGE_TREE_HEIGHT, MAX_RANGE_TREE_HEIGHT) my_tree = tree(tree_height) seq.append(my_tree.values) dataset.append(seq) ################################################################## c_dataset = [] for x in range(COMMON_SEQUENCE_N): seq_range = random.randint(MIN_RANGE_SEQ_LENGTH, MAX_RANGE_SEQ_LENGTH) c_seq = [] for y in range(seq_range): tree_height = random.randint(MIN_RANGE_TREE_HEIGHT, MAX_RANGE_TREE_HEIGHT) my_tree = tree(tree_height) c_seq.append(my_tree.values) c_dataset.append(c_seq) ################################################################## while len(dataset) < N_SEQUENCE:
# 二叉树的深度 from binarytree import Node, tree def GetDepth(t): if t == None: return 0 left = GetDepth(t.left) right = GetDepth(t.right) return max(left, right) + 1 t = tree(3) print(t, GetDepth(t))
from binarytree import tree, Node, bst, build class MyNode: def __init__(self, data, left=None, right=None): self.data = data self.left = left self.right = right a = tree(height=4, is_perfect=False) print(a) b = tree(height=3, is_perfect=True) print(b) c = Node(7) c.left = Node(3) c.right = Node(11) c.left.left = Node(1) c.left.right = Node(5) c.right.left = Node(9) c.right.right = Node(13) print(c) d = build([7, 3, 11, 1, 5, 9, 3]) print(d)
__author__ = 'harshul' from interactivepython.basic.tree import Node #using python package for binary tree: https://pypi.python.org/pypi/binarytree from binarytree import tree, pprint, inspect, convert, heapify mytree = tree(height=2, balanced=True) #pprint(mytree) my_list = [5, 4, 6, 3, 1, 2, 7, 8] # Convert the list into a tree and return its root my_tree = convert(my_list) pprint(my_tree) # Convert the list into a heap and return its root heapify(my_list) my_tree = convert(my_list) pprint(my_tree) # Convert the tree back to a list my_list = convert(my_tree) # Pretty-printing also works on lists pprint(my_list)
class DFSUsingStack: def binaryTreePaths(self, root): if not root: return "" res = [] stack = [] # BOT 0 1 2 3 TOP stack.append([root, ""]) while(stack): node, ls = stack.pop() if not node.left and not node.right: res.append(ls + str(node.value)) if node.right: stack.append([node.right, ls + str(node.value) + "->"]) if node.left: stack.append([node.left, ls + str(node.value) + "->"]) return res # class BFSUsingQueue: # Generate a random binary tree and return its root node my_tree = tree(height=3, is_perfect=False) print(my_tree) method_1 = RecursivePaths() print method_1.binaryTreePaths(my_tree) method_2 = DFSUsingStack() print method_2.binaryTreePaths(my_tree)
if right_min_seen_sum <= left_min_seen_sum and right_min_seen_sum <= root_sum: root_min_seen_node = right_min_seen_node root_min_seen_sum = right_min_seen_sum if left_min_seen_sum <= right_min_seen_sum and left_min_seen_sum <= root_sum: root_min_seen_node = left_min_seen_node root_min_seen_sum = left_min_seen_sum return root_sum, root_min_seen_node, root_min_seen_sum # class Node(object): # # def __init__(self, value, left=None, right=None): # self.val = value # The node value # self.left = left # Left child # self.right = right # Right child if __name__ == '__main__': t = tree(4) print(t) make_some_negative(t) print(t) print(find_min_sum_tree(t).val) root_sum, root_min_seen_node, root_min_seen_sum = find_min_sum_2(t) print(root_min_seen_node.val)
:type t2: Node :rtype: Node """ # Use t1 as the base tree for output if not t1 or not t2: return(t1 if not t2 else t2) else: t1.value += t2.value t1.left = self.mergeTrees(t1.left, t2.left) t1.right = self.mergeTrees(t1.right, t2.right) return(t1) seed(10086) tree1 = tree(height = 3, is_perfect = True) tree2 = tree(height =2, is_perfect = False) print("Tree1") print(tree1) print("Tree2") print(tree2) s = Solution() # When one of the tree argument is empty stree1 = s.mergeTrees(tree1, None) print(stree1) # When both of the tree arguments are empty stree2 = s.mergeTrees(None, None) print(stree2)
def test_setup(): null = -1 class GoodNode(Node): def __init__(self, val, bar=-1, baz=-1): self.foo = val self.bar = bar self.baz = baz class BadNode1(object): def __init__(self, val, bar=-1, baz=-1): self.foo = val self.bar = bar self.baz = baz class BadNode2(object): def __init__(self, val, bar=-2, baz=-2): self.foo = val self.bar = bar self.baz = baz setup_node(node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=null, value_attr='foo', left_attr='bar', right_attr='baz') for _ in range(repetitions): nodes_to_visit = [tree(height=10)] while nodes_to_visit: node = nodes_to_visit.pop() # Check that the new node class is used assert isinstance(node, GoodNode) # Check that the original attributes do not exist assert not hasattr(node, 'left') assert not hasattr(node, 'right') assert not hasattr(node, 'value') # Check that the new attributes are as expected left = attr(node, 'bar') right = attr(node, 'baz') value = attr(node, 'foo') assert isinstance(value, int) if left != null: assert isinstance(left, GoodNode) nodes_to_visit.append(left) if right != null: assert isinstance(right, GoodNode) nodes_to_visit.append(right) setup_node(node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=null, value_attr='foo', left_attr='bar', right_attr='baz') for _ in range(repetitions): nodes_to_visit = [tree(height=10)] while nodes_to_visit: node = nodes_to_visit.pop() # Check that the new node class is used assert isinstance(node, GoodNode) # Check that the original attributes do not exist assert not hasattr(node, 'left') assert not hasattr(node, 'right') assert not hasattr(node, 'value') # Check that the new attributes are as expected left = attr(node, 'bar') right = attr(node, 'baz') value = attr(node, 'foo') assert isinstance(value, int) if left != null: assert isinstance(left, GoodNode) nodes_to_visit.append(left) if right != null: assert isinstance(right, GoodNode) nodes_to_visit.append(right) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: BadNode1(v), node_class=None, null_value=-1, value_attr='foo', left_attr='bar', right_attr='baz', ) assert 'Invalid class given' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=None, node_class=BadNode1, null_value=-1, value_attr='foo', left_attr='bar', right_attr='baz', ) assert 'function must be a callable' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: GoodNode(v), node_class=BadNode1, null_value=-1, value_attr='foo', left_attr='bar', right_attr='baz', ) assert 'returns an instance of "BadNode1"' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=-1, value_attr='value', left_attr='bar', right_attr='baz', ) assert 'required attribute "value"' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=-1, value_attr='foo', left_attr='left', right_attr='baz', ) assert 'required attribute "left"' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=-1, value_attr='foo', left_attr='bar', right_attr='right', ) assert 'required attribute "right"' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: GoodNode(v), node_class=GoodNode, null_value=-1, value_attr='foo', left_attr='bar', right_attr='right', ) assert 'required attribute "right"' in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: BadNode2(v, -2), node_class=BadNode2, null_value=-1, value_attr='foo', left_attr='bar', right_attr='baz', ) assert ('expected null/sentinel value "-1" for its ' 'left child node attribute "bar"') in str(err.value) with pytest.raises(ValueError) as err: setup_node( node_init_func=lambda v: BadNode2(v, -1, -2), node_class=BadNode2, null_value=-1, value_attr='foo', left_attr='bar', right_attr='baz', ) assert ('expected null/sentinel value "-1" for its ' 'right child node attribute "baz"') in str(err.value)
def __init__(self): self.heap = binarytree.tree(height=3, is_perfect=True).values
import numpy as np from binarytree import Node, tree, bst def find_ancestor(node, node1, node2): if node is None: return node if node.value == node1 or node.value == node2: return node x = find_ancestor(node.left, node1, node2) y = find_ancestor(node.right, node1, node2) if x is not None and y is not None: return node return y if x is None else x test_tree = tree(height=4, is_perfect=False) print(test_tree) tree_values = test_tree.values tree_values = list(filter(None, tree_values)) idx1 = int(np.random.randint(0, len(tree_values))) idx2 = int(np.random.randint(idx1, len(tree_values))) val1 = tree_values[idx1] val2 = tree_values[idx2] ancestor_node = find_ancestor(test_tree, val1, val2) print("common ancestor between %d and %d is : %d" % (val1, val2, ancestor_node.value))
#!/usr/bin/env python3 # -*- coding: utf-8 -*- #二叉树遍历 from binarytree import tree my_tree = tree(height=3, is_perfect=False) print(my_tree) root_value = my_tree.value root_left = my_tree.left #1. 先序遍历(根、左、右) def preorder(my_tree): print(my_tree.value) if my_tree.left is not None: preorder(my_tree.left) if my_tree.right is not None: preorder(my_tree.right) if __name__ == "__main__": print("preorder") preorder(my_tree) #1.2 先序遍历非递归(使用栈) from queue import LifoQueue def preorder_stack(my_tree): s = LifoQueue() t = my_tree
from binarytree import tree, bst, heap, pprint # Generate a random binary tree and return its root my_tree = tree(height=5, balanced=False) # Generate a random BST and return its root my_bst = bst(height=5) # Generate a random max heap and return its root my_heap = heap(height=3, max=True) # Pretty print the trees in stdout pprint(my_tree) pprint(my_bst) pprint(my_heap)
def make_some_negative(root): if root is not None: if random.random() > .5: root.val = -root.val make_some_negative(root.left) make_some_negative(root.right) def find_highest_sum(root): if root is None: return 0 left_sum = find_highest_sum(root.left) + root.val right_sum = find_highest_sum(root.right) + root.val if left_sum > right_sum: return left_sum else: return right_sum if __name__ == '__main__': t = tree(2) print(t) make_some_negative(t) print(t) print(find_highest_sum(t))
return root, True elif root.value == val1 or root.value == val2: if left or right: return root, True else: return root, False else: if left: return left, False elif right: return right, False else: return None, False if __name__ == "__main__": print("Python program to find the common ancestor of a tree") n = int(input("what is height of tree?")) my_tree = tree(n) print("The random tree of level %d" % n) pprint(my_tree) while 1: val1 = int(input("enter the value 1:")) val2 = int(input("enter the value 2:")) ans, res = find_anscestor(my_tree, val1, val2) if res: print("The common anscestor of %d and %d is %d" % (val1, val2, ans.value)) else: print("The common anscestor not found")
leftResult = [] rightResult = [] if root is not None: leftResult = [tree_diameter_o_n(root.left)] rightResult = [tree_diameter_o_n(root.right)] height = max(leftResult[0], rightResult[0]) + 1 rootDiameter = leftResult[0] + rightResult[0] + 1 finalDiameter = max(leftResult[1], rightResult[1], rootDiameter) d_and_h[0] = height d_and_h[1] = finalDiameter return d_and_h #testing above code root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.right.right = Node(5) print(tree_diameter_o_n(root)) #testing with python's binarytree package random_tree = tree(4, False) pprint(random_tree) print(tree_diameter_o_n(random_tree))