def check_node_elements(output, tree_array, value): tree = Tree() tree.add(tree_array) node_str = tree.print_node(value) is_correct = check_separeted_text(output, node_str) assert is_correct, '\nОжидал: {}\nПолучил: {}\n'.format(node_str, output)
def check_tree_by_array(output, tree_array): tree = Tree() tree.add(tree_array) tree_str = tree.print_tree() is_correct = check_separeted_text(output, tree_str) assert is_correct, '\nОжидал дерево:\n{}\nПолучил:\n{}\n'.format(tree_str, output)
def setUp(self): self._sub_tree = Node("A", Node("W", Node(1), Node(2)), Node("X", Node(3), Node(4))) self._tree = Tree( "R", self._sub_tree, Node("B", Node("Y", Node(5), Node(6)), Node("Z", Node(7))), )
def setup(self): self.test_tree = Tree() self.test_key_4 = 4 self.test_key_2 = 2 self.test_key_5 = 5 self.test_key_3 = 3 self.test_key_6 = 6 self.test_key_1 = 1 self.test_data = 'test_data'
def build_database(structure, num_keys, key_value_pairs): if structure == 'binary': database = Tree() for i in key_value_pairs: database.insert(i) return database elif structure == 'AVL': database = AVL() for i in key_value_pairs: database.insert(i) return database elif structure == 'hash': database = LPHashTable(num_keys, h_rolling) for i in key_value_pairs: database.insert(i[0], i[1]) return database
def test_find_rand_value(self): bst = Tree() for i in [[10, 1], [12, 2], [11, 3], [14, 4], [13, 5]]: bst.insert(i) for j in range(100): search_for = random.randint(10, 14) r = bst.search(search_for) if search_for == 10: s = [10, 1] elif search_for == 11: s = [11, 3] elif search_for == 12: s = [12, 2] elif search_for == 13: s = [13, 5] elif search_for == 14: s = [14, 4] self.assertEqual(r, s)
def test_insert_rand_values(self): for num in range(100): bst = Tree() L = [] M = [] for i in range(100): rand_int = random.randint(1, 100) if rand_int not in L: L.append(rand_int) for j in L: rand_ints = [] rand_int_2 = random.randint(1, 100) rand_ints.append(j) rand_ints.append(rand_int_2) M.append(rand_ints) for k in M: r = bst.insert(k) self.assertEqual(r, True)
def get_tree(formula_list): if 'ev_' in formula_list: if len(formula_list) != 3: sys.exit("\033[1;31;47m SyntaxError: Improper use of ev_! \033[0m") else: left = None right = get_tree(formula_list[2]) return Tree({'Value': 'ev', 'Bound': convert_bracket(formula_list[1][1:-1])},left,right) elif 'alw_' in formula_list: if len(formula_list) != 3: sys.exit("\033[1;31;47m SyntaxError: Improper use of alw_! \033[0m") else: left = None right = get_tree(formula_list[2]) return Tree({'Value': 'alw', 'Bound': convert_bracket(formula_list[1][1:-1])},left,right) elif 'not_' in formula_list: if len(formula_list) != 2: sys.exit("\033[1;31;47m SyntaxError: Improper use of not_! \033[0m") else: left = None right = get_tree(formula_list[1]) return Tree({'Value': 'not', 'Bound': None},left,right) elif 'and_' in formula_list: if len(formula_list) != 3: sys.exit("\033[1;31;47m SyntaxError: Improper use of and_! \033[0m") else: left = get_tree(formula_list[0]) right = get_tree(formula_list[2]) return Tree({'Value': 'and', 'Bound': None},left,right) elif 'or_' in formula_list: if len(formula_list) != 3: sys.exit("\033[1;31;47m SyntaxError: Improper use of or_! \033[0m") else: left = get_tree(formula_list[0]) right = get_tree(formula_list[2]) return Tree({'Value': 'or', 'Bound': None},left,right) elif 'until_' in formula_list: if len(formula_list) != 4: sys.exit("\033[1;31;47m SyntaxError: Improper use of until_! \033[0m") else: left = get_tree(formula_list[0]) right = get_tree(formula_list[3]) return Tree({'Value': 'until', 'Bound': convert_bracket(formula_list[2][1:-1])},left,right) else: return Tree({'Value': convert_predict(formula_list), 'Bound': None}, None,None)
def test_insert_values(self): bst = Tree() for i in [[10, 1], [12, 2], [17, 3], [14, 4], [15, 5]]: r = bst.insert(i) self.assertEqual(r, True)
def test_insertion(self): sample = Tree(5) test = Tree(14) self.assertEqual(sample.insert(10),test.insert(10))
def test_raise_exception(self): test = Tree(9) test.insert(33) test.insert(56) self.assertRaises(TypeError, test, "hello")
def test_insert_rand_value(self): bst = Tree() k = [random.randint(1, 100), random.randint(1, 100)] r = bst.insert(k) self.assertEqual(r, True)
from binary_tree import Tree def BstInorderFindFirstKeyLargerThan(v, tree): candidate = None curr = tree.get() while curr: if curr.v > v: candidate = curr.v curr = curr.l else: curr = curr.r return candidate if __name__ == "__main__": tree = Tree() tree.add(19) tree.add(7) tree.add(43) tree.add(3) tree.add(11) tree.add(23) tree.add(47) tree.add(2) tree.add(5) tree.add(17) tree.add(37) tree.add(53) tree.add(13) tree.add(29) tree.add(41)
from array_queue import Queue from node import Node from binary_tree import Tree def bfs(tree): queue = Queue() visit_order = [] queue.enqueue(tree.get_root()) while not queue.is_empty(): node = queue.dequeue() visit_order.append(node.value) if node.has_left_child(): queue.enqueue(node.get_left_child()) if node.has_right_child(): queue.enqueue(node.get_right_child()) return visit_order if __name__ == '__main__': tree = Tree("apple") tree.get_root().set_left_child(Node("banana")) tree.get_root().set_right_child(Node("cherry")) tree.get_root().get_left_child().set_left_child(Node("dates")) print(bfs(tree))
from binary_tree import Tree class Solution: def isSymmetric(self, root): """ :type root: TreeNode :rtype: bool """ # def isSame(p, q): # if p and q: # return p.val == q.val and isSame(p.left, q.left) and isSame(p.right, q.right) # return p == q def isSym(p, q): if p and q: return p.val == q.val and isSym(p.left, q.right) and isSym( p.right, q.left) return p == q return isSym(root.left, root.right) if root else True s = Solution() print(s.isSymmetric(Tree([1, 2, 2, 'null', 3, 'null', 3]).root))
def test_insert(self): t = Tree() t.insert(2) self.assertEqual(list(t.display()), [2])
def test_insert_value(self): bst = Tree() r = bst.insert([10, 2]) self.assertEqual(r, True)
def test_find_same_value(self): bst = Tree() for i in [[10, 1], [12, 2], [12, 3], [17, 3], [14, 4], [15, 5]]: bst.insert(i) r = bst.search(12) self.assertEqual(r, [12, 2, 3])
def test_cannot_find_value(self): bst = Tree() for i in [[10, 1], [12, 2], [17, 3], [14, 4], [15, 5]]: bst.insert(i) r = bst.search(20) self.assertEqual(r, False)
from binary_tree import Tree class Solution: def isSameTree(self, p, q): """ :type p: TreeNode :type q: TreeNode :rtype: bool """ if p and q: return p.val == q.val and self.isSameTree( p.left, q.left) and self.isSameTree(p.right, q.right) return p == q t = Tree([1, 2, 3, 'null', 5]) # print(t.root.left.right.val) print(t.BFS()) print(t.DFS())
ret = [] while not ns.is_empty(): n = ns.pop() if n: ret.append(n.val) ns.push(n.right) ns.push(n.left) return ret def dfs_recursive(root): """ 深度遍历,递归实现 :param root: :return: """ if not root: return [] ret = [root.val] ret.extend(dfs_recursive(root.left)) ret.extend(dfs_recursive(root.right)) return ret if __name__ == '__main__': t = Tree([1, 2, 3, 4, 5]) print(dfs(t.root)) print(dfs_recursive(t.root))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None from binary_tree import Tree class Solution(object): def binaryTreePaths(self, root): """ :type root: TreeNode :rtype: List[str] """ l = list() if not (root.left or root.right): return str(root.val) if root.left: l.extend([str(root.val) + '->' + i for i in self.binaryTreePaths(root.left)]) if root.right: l.extend([str(root.val) + '->' + i for i in self.binaryTreePaths(root.right)]) return l print(Solution().binaryTreePaths(Tree([1,2,3,4,5]).root))
def is_bst(node, min_val=None, max_val=None): if min_val is None: min_val = -sys.maxint - 1 if max_val is None: max_val = sys.maxint if node is None: return True if node.value <= min_val or node.value > max_val: return False if (not is_bst(node.leftChild, min_val, node.value) or not is_bst(node.rightChild, node.value, max_val)): return False return True if __name__ == "__main__": bst = Tree() assert bst.insert(40) assert bst.insert(25) assert bst.insert(10) assert bst.insert(32) assert bst.insert(78) assert (is_bst(bst.root))
from binary_tree import Tree, TreeNode class Solution: def inorderTraversal(self, root): """ :type root: TreeNode :rtype: List[int] """ res, l, p = [], [], root while l or p: while p: l.append(p) p = p.left tmp = l.pop() res.append(tmp.val) p = tmp.right return res print(Solution().inorderTraversal(Tree([1, 'null', 2, 3]).root))
from binary_tree import TreeNode, Tree def Soulution(T, n): l = list() def in_order(T): nonlocal l if T == None: return l.append(in_order(T.left)) l.append(T.val) l.append(in_order(T.right)) in_order(T) l = [i for i in l if i is not None] for i in range(len(l)): if l[i] == n: break return [l[i - 1], l[i + 1] ] if 0 < i < len(l) - 1 else [0, l[1]] if i == 0 else [l[-2], 0] if __name__ == '__main__': T = Tree([10, 6, 15, 4, 8, 11, 17, 1, 5]) print(Soulution(T.root, 11))
def test_deletion2(self): test = Tree(9) test.insert(33) test.insert(56) self.assertTrue(test.delete_node(test, 9), 0)
right = check(root.right) print(root.val, left, right) # if left == -1 or right == -1 or abs(left - right) > 1: # return -1 # print(1 + max(left, right)) return 1 + max(left, right) if not root: return True print(root.val, depth(root.right), depth(root.left)) return abs(depth(root.right) - depth(root.left)) <= 1 and self.isBalanced( root.right) and self.isBalanced(root.left) def isBalanced2(self, root): def check(root): if root is None: return 0 left = check(root.left) right = check(root.right) print(root.val, left, right) if left == -1 or right == -1 or abs(left - right) > 1: return -1 # print(1 + max(left, right)) return 1 + max(left, right) return check(root) != -1 s = Solution() print(s.isBalanced(Tree([1, 'null', 3, 2]).root))
def test_insert_same_key(self): bst = Tree() for i in [[10, 1], [12, 2], [17, 3], [14, 4], [15, 5]]: bst.insert(i) r = bst.insert([12, 4]) self.assertEqual(r, False)
在前序遍历中,根节点之后,移动左子树大小的位置,就可以找到右子树 ''' from binary_tree import Tree, TreeNode def construct(qianxu, zhongxu): if not qianxu or not zhongxu: return root = TreeNode(qianxu[0]) pos = zhongxu.index(qianxu[0]) root.left = construct(qianxu[1:pos + 1], zhongxu[0:pos]) root.right = construct(qianxu[pos + 1:], zhongxu[pos + 1:]) return root if __name__ == '__main__': qianxu = [ 50, 38, 29, 20, 14, 7, 25, 32, 36, 48, 41, 49, 91, 67, 59, 52, 60, 64, 66, 85, 70, 87, 98, 94, 100, 99 ] zhongxu = [ 7, 14, 20, 25, 29, 32, 36, 38, 41, 48, 49, 50, 52, 59, 60, 64, 66, 67, 70, 85, 87, 91, 94, 98, 99, 100 ] root = construct(qianxu, zhongxu) t = Tree() t.bianli_ceng(root) # [50, 38, 91, 29, 48, 67, 98, 20, 32, 41, 49, 59, 85, 94, 100, 14, 25, 36, 52, 60, 70, 87, 99, 7, 64, 66]
def test_deletion(self): sample = Tree(14) sample.insert(2) sample.insert(56) self.assertNotEqual(sample.delete_node(sample, 56), 0)