예제 #1
0
def is_subtree(subroot, root):
    if not subroot and not root:
        return True
    if not subroot or not root:
        return False
    return is_same_tree(subroot, root) or \
           is_subtree(subroot, root.left) or \
           is_subtree(subroot, root.right)
예제 #2
0
def test_nontrivial_true():
    #        6
    #      /   \
    #     2     8
    #    / \   / \
    #   1   3 7   9
    L = [1, 2, 3, 6, 7, 8, 9]
    tree = array_to_bst(L)
    expected = TreeNode(6)
    expected.left = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
    expected.right = TreeNode(8, left=TreeNode(7), right=TreeNode(9))
    assert is_same_tree(tree, expected)
예제 #3
0
def test_nontrivial():
    #        4               4
    #      /   \           /   \
    #     2     7   ->    7     2
    #    / \   / \       / \   / \
    #   1   3 6   9     9   6 3   1

    tree = TreeNode(4)
    tree.left = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
    tree.right = TreeNode(7, left=TreeNode(6), right=TreeNode(9))

    tree_inv = TreeNode(4)
    tree_inv.left = TreeNode(7, left=TreeNode(9), right=TreeNode(6))
    tree_inv.right = TreeNode(2, left=TreeNode(3), right=TreeNode(1))

    assert is_same_tree(invert(tree), tree_inv)
예제 #4
0
def test_nontrivial_false():
    #        4               4
    #      /   \           /   \
    #     2     7   !=    7     2
    #    /     / \       / \   / \
    #   1     6   9     9   6 3   1

    tree1 = TreeNode(4)
    tree1.left = TreeNode(2, left=TreeNode(1))
    tree1.right = TreeNode(7, left=TreeNode(6), right=TreeNode(9))

    tree2 = TreeNode(4)
    tree2.left = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
    tree2.right = TreeNode(7, left=TreeNode(6), right=TreeNode(9))

    assert not is_same_tree(tree1, tree2)
예제 #5
0
def test_nontrivial_true():
    #        4               4
    #      /   \           /   \
    #     2     7   ==    2     7
    #    / \   / \       / \   / \
    #   1   3 6   9     1   3 6   9

    tree1 = TreeNode(4)
    tree1.left = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
    tree1.right = TreeNode(7, left=TreeNode(6), right=TreeNode(9))

    tree2 = TreeNode(4)
    tree2.left = TreeNode(2, left=TreeNode(1), right=TreeNode(3))
    tree2.right = TreeNode(7, left=TreeNode(6), right=TreeNode(9))

    assert is_same_tree(tree1, tree2)
예제 #6
0
def test_trivial():
    tree = TreeNode(0)
    tree_inv = invert(tree)
    assert is_same_tree(tree_inv, TreeNode(0))
예제 #7
0
def test_trivial_true():
    tree1 = TreeNode(0)
    tree2 = TreeNode(0)
    assert is_same_tree(tree1, tree2)
예제 #8
0
def test_trivial_false():
    tree1 = TreeNode(0)
    tree2 = TreeNode(1)
    assert not is_same_tree(tree1, tree2)