예제 #1
0
def minimal_tree(lst):
    """time: O(n) space: O(n)"""
    if not lst: return None
    middle = len(lst) // 2
    root = BinaryNode(lst[middle])
    root.left = minimal_tree(lst[:middle])
    root.right = minimal_tree(lst[middle+1:])
    return root
예제 #2
0
def test_invalid_bst(fn):

    #      8
    #     / \
    #    4   10
    #   / \   \
    #  2   12  20

    n2 = BinaryNode(2)
    n12 = BinaryNode(12)
    n4 = BinaryNode(4, left=n2, right=n12)
    n20 = BinaryNode(20)
    n10 = BinaryNode(10, right=n20)
    n8 = BinaryNode(8, left=n4, right=n10)

    assert fn(n8) == False
예제 #3
0
def test_valid_bst(fn):

    #      8
    #     / \
    #    4   10
    #   / \   \
    #  2   6   20

    n2 = BinaryNode(2)
    n6 = BinaryNode(6)
    n4 = BinaryNode(4, left=n2, right=n6)
    n20 = BinaryNode(20)
    n10 = BinaryNode(10, right=n20)
    n8 = BinaryNode(8, left=n4, right=n10)

    assert fn(n8) == True
예제 #4
0
def test_list_of_depth(fn):

    #      8
    #     / \
    #    4   10
    #   / \   \
    #  2   6   20

    n2 = BinaryNode(2)
    n6 = BinaryNode(6)
    n4 = BinaryNode(4, left=n2, right=n6)
    n20 = BinaryNode(20)
    n10 = BinaryNode(10, right=n20)
    n8 = BinaryNode(8, left=n4, right=n10)

    levels = list_of_depths(n8)
    levels = [map(lambda node: node.value, level) for level in levels]
    assert levels == [[8], [4, 10], [2, 6, 20]]
예제 #5
0
def test_complex(fn):

    #      3
    #     / \
    #    2   5
    #   /   / \
    #  1   4   6

    n1 = BinaryNode(1)
    n2 = BinaryNode(2, left=n1)
    n4 = BinaryNode(4)
    n6 = BinaryNode(6)
    n5 = BinaryNode(5, left=n4, right=n6)
    root = BinaryNode(3, left=n2, right=n5)
    assert fn(root) == True

    #      3
    #     / \
    #    2   5
    #   /   / \
    #  1   4   6
    #           \
    #            7

    n7 = BinaryNode(7)
    n6.right = n7
    assert fn(root) == True

    #      3
    #     / \
    #    2   5
    #   /   / \
    #  1   4   6
    #           \
    #            7
    #             \
    #              8

    n8 = BinaryNode(8)
    n7.right = n8
    assert fn(root) == False
예제 #6
0
def test_degenerate(fn):
    root = BinaryNode(1, right=BinaryNode(2, right=BinaryNode(3)))
    assert fn(root) == False
예제 #7
0
def test_only_right_child(fn):
    root = BinaryNode(1, right=BinaryNode(2))
    assert fn(root) == True
예제 #8
0
def test_only_left_child(fn):
    root = BinaryNode(1, left=BinaryNode(2))
    assert fn(root) == True
예제 #9
0
def test_only_root(fn):
    root = BinaryNode(1)
    assert fn(root) == True