def _put(self, key, val, curr_node): if key < curr_node.key: if curr_node.hasLeftChild(): self._put(key, val, curr_node.leftChild) else: curr_node.leftChild = TreeNode(key, val, parent=curr_node) self.update_balance(curr_node.leftChild) else: if curr_node.hasRightChild(): self._put(key, val, curr_node.rightChild) else: curr_node.rightChild = TreeNode(key, val, parent=curr_node) self.update_balance(curr_node.rightChild)
def minimal_tree(vals): """ Creates a binary search tree with minimal height given an array of sorted integers """ if not vals: return None n = len(vals) root = TreeNode(vals[n // 2]) root.left = minimal_tree(vals[0:n // 2]) root.right = minimal_tree(vals[n // 2 + 1:]) return root
def huffman(C): n = len(C) Q = C for i in range(1, n): x = extract_min(Q) y = extract_min(Q) z = TreeNode(x.data + y.data, None, x, y) insert(Q, z) return extract_min(q)
def test_can_create_complex_tree(self): expected = TreeNode( '4', TreeNode('2', TreeNode('1', None, None), TreeNode('3', None, None)), TreeNode('6', TreeNode('5', None, None), TreeNode('7', None, None))) self.assertTreeEqual( BinarySearchTree(['4', '2', '6', '1', '3', '5', '7']).data(), expected)
def test_can_create_complex_tree(self): expected = TreeNode( "4", TreeNode("2", TreeNode("1", None, None), TreeNode("3", None, None)), TreeNode("6", TreeNode("5", None, None), TreeNode("7", None, None)), ) self.assertTreeEqual( BinarySearchTree(["4", "2", "6", "1", "3", "5", "7"]).data(), expected)
def insert_one(self, value, node=None): if self.empty(): self.root = TreeNode(value) return new_node = TreeNode(value) if node == None: node = self.root if value < node.val: if node.left == None: new_node.parent = node node.left = new_node else: self.insert_one(value, node.left) else: if node.right == None: new_node.parent = node node.right = new_node else: self.insert_one(value, node.right) self.update()
def check_sequences(tree, sequences): """ Creates a tree for each sequence in sequence and checks if it is equal to the original tree that generated all the sequences """ for sequence in sequences: root, *rest = sequence sequence_tree = TreeNode(root) for val in rest: sequence_tree.insert(val) if not is_equal(tree, sequence_tree): print(sequence) sequence_tree.display() return False return True
for sequence in sequences: root, *rest = sequence sequence_tree = TreeNode(root) for val in rest: sequence_tree.insert(val) if not is_equal(tree, sequence_tree): print(sequence) sequence_tree.display() return False return True if __name__ == "__main__": tree = TreeNode(randint(0, 100)) for _ in range(6): tree.insert(randint(0, randint(0, 100))) print('--- Original Tree ---') tree.display() print('\n--- Weaved ---') sequences = all_sequences(tree) print('\n--- BST Sequences ---') for sequence in sequences: print(sequence) print('\n--- Checking Equality Between Sequences ---') if check_sequences(tree, sequences):
if not T1 and not T2: return True # One empty if not T1 or not T2: return False # Non-equal values if T1.val != T2.val: return False # Otherwise, check that subtrees are equivalent return is_equal(T1.left, T2.left) and is_equal(T1.right, T2.right) # -- Testing from random import randint, seed if __name__ == "__main__": seed(1209) T1 = TreeNode(50) for _ in range(50): T1.insert(randint(0, 100)) T1.display() T2 = T1.search(42) T2.display() print(check_subtree(T1, T2))
def test_same_number_at_left_node(self): expected = TreeNode('4', TreeNode('4', None, None), None) self.assertTreeEqual(BinarySearchTree(['4', '4']).data(), expected)
""" An iterative solution with O(N) time complexity and O(1) space complexity """ node = root while node: if n1.val > node.val and n2.val > node.val: node = node.right elif n1.val < node.val and n2.val < node.val: node = node.left else: return node # -- Testing from random import randint, seed if __name__ == "__main__": seed(69) tree = TreeNode(50) for _ in range(25): tree.insert(randint(0, 100)) tree.display() print('---') node0, node1 = tree.search(41), tree.search(56) print(f'Nodes: {node0} {node1}') print(f'LCA: {lca(tree, node0, node1)}') print(f'LCA: {lowest_common_ancestor(tree, node0, node1)}')
def test_insert(): tree = BinarySearchTree(50) tree.insert(25) assert tree.root == TreeNode(50, left=TreeNode(25)) tree.insert(75) assert tree.root == TreeNode(50, left=TreeNode(25), right=TreeNode(75)) tree.insert(100) assert tree.root == TreeNode(50, left=TreeNode(25), \ right=TreeNode(75, right=TreeNode(100))) tree.insert(0) assert tree.root == TreeNode(50, left=TreeNode(25, left=TreeNode(0)), \ right=TreeNode(75, right=TreeNode(100)))
def test_init(): tree = BinarySearchTree(50) assert tree.root == TreeNode(50)
t.assertAlmostEqual(None, tree.inorder_successor(20)) t.assertAlmostEqual(60, tree.inorder_successor(50)) t.assertAlmostEqual(None, tree.inorder_successor(55)) t.assertAlmostEqual(70, tree.inorder_successor(60)) t.assertAlmostEqual(None, tree.inorder_successor(65)) t.assertAlmostEqual(80, tree.inorder_successor(70)) t.assertAlmostEqual(None, tree.inorder_successor(85)) t.assertAlmostEqual(100, tree.inorder_successor(90)) t.assertAlmostEqual(None, tree.inorder_successor(95)) t.assertAlmostEqual(None, tree.inorder_successor(100)) t.assertAlmostEqual(None, tree.inorder_successor(110)) tree = Tree() tree.search(50) node100 = TreeNode(100) node50 = TreeNode(50) node200 = TreeNode(200) node25 = TreeNode(25) node125 = TreeNode(125) node350 = TreeNode(350) node50.left = node25 node200.left = node125 node200.right = node350 node100.left = node50 node100.right = node200 tree.root = node100 t.assertEqual(id(node100), id(tree.search(100))) t.assertEqual(id(node50), id(tree.search(50))) t.assertEqual(id(node200), id(tree.search(200)))
class Solution(object): def searchBST(self, root, val): """ :type root: TreeNode :type val: int :rtype: TreeNode """ if root is None: return None elif root.val == val: return root elif root.val > val: return self.searchBST(root.left, val) elif root.val < val: return self.searchBST(root.right, val) if __name__ == "__main__": bstArr = [4, 2, 7, 1, 3] bst = BinarySearchTree(bstArr=bstArr) root = TreeNode(val=bst.bstArr[0], left=None, right=None) bst.constructBST(root, 0) print("BST Constructed") bst.printBST(root) node = Solution().searchBST(root=root, val=7) if node is not None: print("Found TreeNode: {}".format(node.val)) else: print("Node not found")
return float('-inf') right_height = check_height(root.right) if right_height == float('-inf'): # Pass error up return float('-inf') height_diff = abs(left_height - right_height) if height_diff > 1: return float('-inf') return max(left_height, right_height) + 1 # -- Testing from binary_search_tree import TreeNode from random import randint if __name__ == "__main__": root = TreeNode(50) for _ in range(10): root.insert(randint(25, 75)) root.display() print(check_balanced(root)) # True or False print('-' * 50) minimal = minimal_tree([1, 2, 3, 4, 5, 6, 7, 8]) minimal.display() print(check_balanced(minimal)) # True
if not root: return 0 return (paths_with_sum(root.left, target) + paths_with_sum(root.right, target) + pws_helper(root, 0, target)) def pws_helper(node, curr, target): if not node: return 0 curr += node.val return (1 if curr == target else 0 + pws_helper(node.left, curr, target) + pws_helper(node.right, curr, target)) # -- Testing from binary_search_tree import TreeNode from random import randint, seed if __name__ == "__main__": tree = TreeNode(5) for _ in range(25): tree.insert(randint(0, 20)) tree.display() target = 38 total_paths = paths_with_sum(tree, target) print(f'\nPaths with sum {target}: {total_paths} path(s)')
def test_smaller_data_at_left_node(self): expected = TreeNode('4', TreeNode('2', None, None), None) self.assertTreeEqual(BinarySearchTree(['4', '2']).data(), expected)
def test_smaller_number_at_left_node(self): expected = TreeNode("4", TreeNode("2", None, None), None) self.assertTreeEqual(BinarySearchTree(["4", "2"]).data(), expected)
def test_greater_number_at_right_node(self): expected = TreeNode('4', None, TreeNode('5', None, None)) self.assertTreeEqual(BinarySearchTree(['4', '5']).data(), expected)
def test_greater_number_at_right_node(self): expected = TreeNode("4", None, TreeNode("5", None, None)) self.assertTreeEqual(BinarySearchTree(["4", "5"]).data(), expected)
def test_data_is_retained(self): expected = TreeNode('4', None, None) self.assertTreeEqual(BinarySearchTree(['4']).data(), expected)
def validate_bst_util(node, low, high): """ Helper function for validating a binary search tree """ if not node: return True if not low < node.val < high: return False return validate_bst_util(node.left, low, node.val) and \ validate_bst_util(node.right, node.val, high) # -- Testing from binary_search_tree import TreeNode from random import randint if __name__ == "__main__": invalid_tree = TreeNode(4, TreeNode(5), TreeNode(6)) invalid_tree.display() print(validate_bst(invalid_tree)) print('-' * 25) valid_tree = TreeNode(10) for _ in range(20): valid_tree.insert(randint(0, 20)) valid_tree.display() print(validate_bst(valid_tree))