def test_right_left_conversion_six_nodes(): """ Test that given six nodes in a left-right state converts to left-left. """ from bst import Bst, Node new_bst = Bst() node1 = Node(10) node2 = Node(5) node3 = Node(15) node4 = Node(20) node5 = Node(14) node6 = Node(13) new_bst.head = node1 node1.left = node2 node2.parent = node1 node1.right = node3 node3.parent = node1 node3.right = node4 node4.parent = node3 node3.left = node5 node5.parent = node3 node5.left = node6 node6.parent = node5 new_bst.head.right_left_conversion() assert new_bst.head.right == node5 assert new_bst.head.right.right == node3 assert new_bst.head.right.right.right == node4
def main(): complete_binary_tree = BST() one = Node(1) two = Node(2) three = Node(3) four = Node(4) five = Node(5) six = Node(6) seven = Node(7) one.left = two one.right = three two.left = four two.right = five three.left = six three.right = seven complete_binary_tree.root = one add_sibling_pointers(complete_binary_tree.root) nodes = list(complete_binary_tree.levelorder_nodes()) # verify the next pointers assert one.next is None assert two.next is three assert three.next is None assert four.next is five assert five.next is six assert six.next is seven assert seven.next is None
def main(): one = Node(1, "") two = Node(2, "") three = Node(3, "") four = Node(4, "") five = Node(5, "") six = Node(6, "") seven = Node(7, "") eight = Node(8, "") nine = Node(9, "") one.left = two one.right = three two.left = four two.right = five three.left = six three.right = seven five.left = eight five.right = nine assert five is LCA(one, eight, nine) assert two is LCA(one, two, nine) assert one is LCA(one, two, seven) assert one is LCA(one, one, nine) assert four is LCA(one, four, four)
def main(): one = Node(1, "") two = Node(2, "") three = Node(3, "") four = Node(4, "") five = Node(5, "") six = Node(6, "") seven = Node(7, "") eight = Node(8, "") nine = Node(9, "") one.left = two one.right = three two.left = four two.right = five four.left = six four.right = seven tree = Tree() tree.root = one tree.levelorder() inverted = upside_down(tree) inverted.levelorder()
def test_bst_left_setter_child(): """test that left child setter works""" from bst import Node node1 = Node(9) node2 = Node(7) node1.left = node2 assert node1.left.val == node2.val
def test_bst_left_setter_parent(): """test that left child setter sets parent""" from bst import Node node1 = Node(9) node2 = Node(7) node1.left = node2 assert node2.parent.val == node1.val
def _create_min_bst(self, array, start, end): if end < start: return None mid = (start + end) // 2 node = Node(array[mid]) node.left = self._create_min_bst(array, start, mid - 1) node.right = self._create_min_bst(array, mid + 1, end) return node
def test_rotate_right(): from bst import Node node1 = Node() node2 = Node() node2.left = node1 node1.rotate_right() assert node1.right == node2 assert not node2.left
def test_bst_del_left_child(): """test deleter on left child""" from bst import Node node1 = Node(9) node2 = Node(7) node1.left = node2 del node1.left assert node1.left is None
def test_right_rotation_three_nodes(): """Test that a left-left becomes balanced.""" from bst import Bst, Node new_bst = Bst() node1 = Node(15) node2 = Node(10) node3 = Node(5) new_bst.head = node1 node1.left = node2 node2.parent = node1 node2.left = node3 node3.parent = node2 new_bst.head.right_rotation() assert node2.parent is None assert node2.right == node1 assert node2.left == node3 assert node2.right.parent == node2
def balanced_bst_from_sorted_array(arr, start, end): if start > end: return mid = (start + end) / 2 root = Node(arr[mid]) root.left = balanced_bst_from_sorted_array(arr, start, mid - 1) root.right = balanced_bst_from_sorted_array(arr, mid + 1, end) return root
def main(): _50 = Node(50, "hello") _25 = Node(25, "hello") _75 = Node(75, "hello") _12 = Node(12, "hello") _34 = Node(34, "hello") _60 = Node(60, "hello") _80 = Node(80, "hello") _55 = Node(55, "hello") _22 = Node(22, "hello") _50.left = _25 _50.right = _75 _25.left = _12 _25.right = _34 _75.left = _60 _75.right = _80 _12.right = _55 assert False is is_bst(_50) _12.right = _22 assert True is is_bst(_50) tree = BST() N = 10 for _ in range(N): tree.insert(random.randint(1, 100), "hello") assert True is is_bst(tree.root) # skewed tree tree = BST() for n in range(N): tree.insert(n, "hello") assert True is is_bst(tree.root) # skewed tree tree = BST() for n in range(N, 0, -1): tree.insert(n, "hello") assert True is is_bst(tree.root)
def __clone(node): if not node: return new_root = Node(node.key, node.data) new_left = __clone(node.left) new_right = __clone(node.right) new_root.left = new_left new_root.right = new_right return new_root
def test_Node_depth(): from bst import Node node1 = Node() node2 = Node() node3 = Node() node4 = Node() node1.left = node2 node1.right = node3 node3.right = node4 results = [node1.depth, node2.depth, node3.depth] assert results == [3, 1, 2]
def _sorted_array_to_bst(array, left, right): if left == right: return Node(array[left]) if left > right: return None mid = (left + right) / 2 root = Node(array[mid]) root.left = _sorted_array_to_bst(array, left, mid-1) root.right = _sorted_array_to_bst(array, mid+1, right) return root
def build_tree(in_order_list, pre_order_list): if pre_order_list and in_order_list: root_val = pre_order_list.pop(0) root = Node(root_val) in_order_index = in_order_list.index(root_val) root.left = build_tree(in_order_list[:in_order_index], pre_order_list) root.right = build_tree(in_order_list[in_order_index + 1:], pre_order_list) return root else: return None
def filled_tree(): A = Node(6) a = BST() a.root = A A.left = 4 A.right = 7 A.left.left = 3 A.left.right = 5 A.right.right = 8 a._size = 6 return a
def uneven_tree(): A = Node(6) a = BST() a.root = A A.left = 4 A.right = 7 A.left.left = 3 A.left.right = 5 A.right.right = 8 A.right.right.right = 9 A.right.right.right.right = 10 a._size = 6 return a
def test_right_left_conversion_three_nodes(): """ Test that given three nodes in a right-left state converts to right-right. """ from bst import Bst, Node new_bst = Bst() node1 = Node(10) node2 = Node(15) node3 = Node(12) new_bst.head = node1 node1.right = node2 node2.parent = node1 node2.left = node3 node3.parent = node2 new_bst.head.right_left_conversion() assert new_bst.head.right == node3 assert new_bst.head.right.right == node2 assert new_bst.head.right.right.parent == node3 assert new_bst.head.right.parent == node1
def binary_tree_from_traversals(preorder, inorder): if not preorder: return None if not inorder: return None root_key = preorder[0] root = Node(root_key) inorder_left, preorder_left, inorder_right, preorder_right = get_traversals_for_subtrees( root_key, inorder, preorder) # print "root: %s, inorder_left: %s, preorder_left: %s" % (root_key, inorder_left, preorder_left) # print "root: %s, inorder_right: %s, preorder_right: %s" % (root_key, inorder_right, preorder_right) # print "------" if inorder_left: root.left = binary_tree_from_traversals(preorder_left, inorder_left) if inorder_right: root.right = binary_tree_from_traversals(preorder_right, inorder_right) return root
from bst import Node from bst import BinarySearchTree # 8 # / \ # 3 9 # \ # 11 node1 = Node(8) node2 = Node(3) node3 = Node(9) node4 = Node(11) #make Node(8) children Node(3) and Node(9) node1.left = node2 node1.right = node3 #make Node(11) right child of Node(9) node3.right = node4 #have built a tree #search the tree for a target value #imagine we are searching for 11 root = node1 target = 11 # if root.data == target: # print("Found it!")
# Implement a function to check if a binary tree is a binary tree from bst import Node def is_bst(tree, min_limit=None, max_limit=None): if tree is None: return True if min_limit is not None and tree.item < min_limit: return False if max_limit is not None and tree.item > max_limit: return False if not is_bst(tree.left, min_limit, tree.item): return False if not is_bst(tree.right, tree.item, max_limit): return False return True if __name__ == '__main__': valid = Node(5) valid.left = Node(0) valid.left.left = Node(-1) valid.left.right = Node(1) valid.right = Node(10) valid.right.left = Node(6) valid.right.left.left = Node(5.5) valid.right.left.left.left = Node(4.9) print(is_bst(valid))
print(root.data) for node in get_neigbhor(root): if node not in visited: visited.add(node) dfs_better(node, visited) def get_neigbhor(root): l = [] if root.left: l.append(root.left) if root.right: l.append(root.right) return l from bst import Node root = Node(4) root.left = Node(2) root.right = Node(6) root.left.left = Node(1) root.left.right = Node(3) root.right.left = Node(5) root.right.right = Node(7) print("dfs_better:") dfs_better(root)
deepest = current deepest_depth = depth # Each O(2n) happening n times for n nodes below current left_node, left_depth = first_common_ancestor(current.left, node1, node2, deepest, deepest_depth, depth + 1) right_node, right_depth = first_common_ancestor(current.right, node1, node2, deepest, deepest_depth, depth + 1) if left_depth >= right_depth: return left_node, left_depth return right_node, right_depth if __name__ == '__main__': tree = Node(5) tree.left = Node(10) tree.right = Node(20) tree.left.left = Node(0) tree.left.right = Node(500) print(tree) # print(is_descendent(tree, tree.right)) print("anc") common, depth = first_common_ancestor(tree, tree.left.left, tree.left.right) print(common) print(depth)
def test_node_left_deleter(): from bst import Node node = Node(5) node.left = Node(3) del node.left assert node.left is None
if is_first and (found_left_second or found_right_second): # if the current node is first then look for the second in the decendents return (root, True, True) if is_second and (found_left_first or found_right_first): # if the current node is second then look for the first in the decendents return (root, True, True) return (None, is_first or found_left_first or found_right_first, is_second or found_left_second or found_right_second) if __name__ == '__main__': tree = Node(1) tree.left = Node(2) tree.left.left = Node(4) tree.left.right = Node(5) tree.right = Node(3) tree.right.right = Node(7) tree.right.left = Node(6) bst.print_levels(tree) print() print('lca(1,2)=', find_lca(tree, 1, 2).value) print('lca(4,5)=', find_lca(tree, 4, 5).value) print('lca(4,6)=', find_lca(tree, 4, 6).value) print('lca(3,4)=', find_lca(tree, 3, 4).value) print('lca(2,4)=', find_lca(tree, 2, 4).value) print('lca(6,7)=', find_lca(tree, 6, 7).value) print('lca(2,3)=', find_lca(tree, 2, 3).value)
def test_Node_setting_left(): from bst import Node node1 = Node() node2 = Node() node1.left = node2 assert node1.left == node2
def test_balance_left(): """Test that a left side is larger and returns a positive int.""" from bst import Node a = Node(20) a.left = Node(18) assert a.balance() == 1
def test_depth_many(): """Test that a node with one extra on the left has a depth of 2.""" from bst import Node a = Node(20) a.left = Node(16) assert a.depth() == 2
def build_tree(in_order_list, pre_order_list): if pre_order_list and in_order_list: root_val = pre_order_list.pop(0) root = Node(root_val) in_order_index = in_order_list.index(root_val) root.left = build_tree(in_order_list[:in_order_index], pre_order_list) root.right = build_tree(in_order_list[in_order_index + 1:], pre_order_list) return root else: return None if __name__ == '__main__': tree = Node(17) tree.left = Node(6) tree.left.left = Node(3) tree.left.right = Node(9) tree.left.right.left = Node(7) tree.left.right.right = Node(13) tree.right = Node(21) tree.right.right = Node(24) tree.right.right.left = Node(22) tree.right.right.right = Node(26) assert (bst.is_bst(tree)) bst.print_in_order(tree) print() bst.print_pre_order(tree) print()
# while current: # if current.item == target_item: # return depth # if target_item < current.item: # current = current.left # else: # current = current.right # depth += 1 # return None # strategy, traverse the bst and keep a record of the depth of everything # Keep a dict of depth mappings to linked lists def list_of_depths(tree, depths, depth=0): if tree is None: return depths[depth].add(tree.item) list_of_depths(tree.left, depths, depth+1) list_of_depths(tree.right, depths, depth+1) if __name__ == '__main__': tree = Node(0) tree.left = Node(-2) tree.left.left = Node(-3) tree.left.right = Node(-1) tree.right = Node(5) tree.right.right = Node(6) depths = defaultdict(LinkedList) list_of_depths(tree, depths) print(dict(depths))
elif t1.item != t2.item: return False elif not verify(t1.left, t2.left): return False elif not verify(t1.right, t2.right): return False return True def check_subtree(t1, t2): """ Returns true if t2 is a subtree of t1 """ t1_node = find(t1, t2) if t1_node is None: return False return verify(t1_node, t2) if __name__ == '__main__': t1 = Node(5) t1.left = Node(0) t1.right = Node(10) t1.right.right = Node(50) t1.right.right.right = Node(500) t2 = Node(10) t2.right = Node(50) t2.right.right = Node(500) print(check_subtree(t1, t2))
if tree is None: return True height_left = get_height(tree.left) height_right = get_height(tree.right) if abs(height_left - height_right) > 1: return False if not is_balanced(tree.left): return False if not is_balanced(tree.right): return False return True if __name__ == '__main__': balanced_tree = Node(2) balanced_tree.left = Node(1) balanced_tree.left.left = Node(0) balanced_tree.left.left.left = Node(-1) balanced_tree.left.left.right = Node(0.5) balanced_tree.left.right = Node(1.5) balanced_tree.right = Node(8) balanced_tree.right.left = Node(7) balanced_tree.right.left.left = Node(6) balanced_tree.right.right = Node(20) test = Node(5) test.left = Node(2) test.right = Node(10) # heights = {} # get_heights(test, heights)
return paths_from_root + paths_on_left + paths_on_right def count_paths_with_sum_from_node(node, target_sum, current_sum): if node is None: return 0 current_sum += node.item total_paths = 0 if current_sum == target_sum: # Found a path from the root total_paths += 1 total_paths += count_paths_with_sum_from_node(node.left, target_sum, current_sum) total_paths += count_paths_with_sum_from_node(node.right, target_sum, current_sum) return total_paths def paths_with_sum(value): pass if __name__ == '__main__': t = Node(5) t.left = Node(1) t.right = Node(4) t.right.right = Node(1) t.right = Node(0) print(count_paths_with_sum(t, 6))