def test_find_bst_sequences(): bst = BinarySearchTree() bst.insert(2) bst.insert(1) bst.insert(3) sequences = find_bst_sequences(bst) assert [2, 1, 3] in sequences assert [2, 3, 1] in sequences assert len(sequences) == 2
def test_in_order_successor(): bst = BinarySearchTree() bst.insert(20) bst.insert(9) bst.insert(25) bst.insert(5) bst.insert(12) bst.insert(11) bst.insert(14) # Test all nodes inputs = [5, 9, 11, 12, 14, 20, 25] outputs = inputs[1:] outputs.append(None) for x, y in zip(inputs, outputs): test = bst.get_node(x) succ = in_order_successor(test) if succ is not None: assert succ.key == y else: assert succ == y
if input_node.right: current = input_node.right while current.left: current = current.left return current else: ancestor = input_node.parent child = input_node while ancestor and ancestor.right == child: child = ancestor ancestor = ancestor.parent return ancestor if __name__ == "__main__": bst = BinarySearchTree() bst.insert(20) bst.insert(9) bst.insert(25) bst.insert(5) bst.insert(12) bst.insert(11) bst.insert(14) # Get a reference to the node whose key is 9 test = bst.get_node(12) # Find the in order successor of test succ = in_order_successor(test) # Print the key of the successor node
def example(): bst = BinarySearchTree() bst.insert(20) bst.insert(9) bst.insert(25) bst.insert(5) bst.insert(12) # bst.insert(11); # bst.insert(14); sequences = find_bst_sequences(bst) print(sequences)
def test_is_binary_search_tree(): bst = BinarySearchTree() bst.insert(20) bst.insert(9) bst.insert(25) bst.insert(5) bst.insert(12) bst.insert(11) bst.insert(14) t = BinaryTree() n1 = t.insert(5, None) n2 = t.insert(4, n1) n3 = t.insert(6, n1) n4 = t.insert(3, n2) t.insert(6, n2) t.insert(5, n3) t.insert(2, n4) assert not is_binary_search_tree(t) assert is_binary_search_tree(bst)