for x in range(tree_one_preorder.count('x')):
        tree_one_preorder.remove('x')

    for x in range(tree_two_preorder.count('x')):
        tree_two_preorder.remove('x')

    str_tree_one = ''.join(str(e) for e in tree_one_preorder)
    str_tree_two = ''.join(str(e) for e in tree_two_preorder)

    if str_tree_two in str_tree_one:
        print('T2 is a Subtree from T1')
        return True
    else:
        print('T2 is NOT a Subtree from T1')
        return False


# T2 is subtree
list_nodes_t1 = [1, 2, 3, 4, 5, 6, 7]
list_nodes_t2 = [5, 6, 7]
root_tree_one = create_tree(list_nodes_t1, 0, len(list_nodes_t1) - 1)
root_tree_two = create_tree(list_nodes_t2, 0, len(list_nodes_t2) - 1)
check_is_sub_tree(root_tree_one, root_tree_two)

# T2 is not subtree
list_nodes_t1 = [1, 2, 3, 4, 5, 6, 7]
list_nodes_t2 = [5, 6, 7, 8]
root_tree_one = create_tree(list_nodes_t1, 0, len(list_nodes_t1) - 1)
root_tree_two = create_tree(list_nodes_t2, 0, len(list_nodes_t2) - 1)
check_is_sub_tree(root_tree_one, root_tree_two)
Ejemplo n.º 2
0

def check_bst(root_node):
    if root_node.left_son == None and root_node.right_son == None:
        return True

    if root_node.left_son == None and root_node.right_son != None and root_node.data <= get_min(
            root_node.right_son):
        return True and check_bst(root_node.right_son)

    if root_node.left_son != None and root_node.right_son == None and root_node.data >= get_max(
            root_node.left_son):
        return True and check_bst(root_node.left_son)

    max_value_left = get_max(root_node.left_son)
    min_value_right = get_min(root_node.right_son)

    if max_value_left <= root_node.data and root_node.data <= min_value_right:
        return True and check_bst(root_node.left_son) and check_bst(
            root_node.right_son)

    return False


sorted_array = [0, 1, 2, 3, 4, 5, 6, 7]
root_node = create_tree(sorted_array, 0, len(sorted_array) - 1)
sorted_array2 = [0, 1, 8, 3, 4, 5, 6, 7]
root_node2 = create_tree(sorted_array2, 0, len(sorted_array2) - 1)
print(check_bst(root_node))
print(check_bst(root_node2))
Ejemplo n.º 3
0
from Helper import Node, create_tree

# Create balanced tree
sorted_array = [0, 1, 2, 3, 4, 5, 6, 7]
root_node_balanced = create_tree(sorted_array, 0, len(sorted_array) - 1)

# Create unbalanced tree
root_node_unbalanced = Node(2)
left_root_son = root_node_unbalanced.left_son = Node(0)
right_root_son = root_node_unbalanced.left_son = Node(1)
right_root_son.left_son = Node(0)
right_root_son.right_son = Node(1).right_son = Node(0)


def get_height(root_node, depth):
    if root_node == None:
        return depth

    left_height = get_height(root_node.left_son, depth + 1)
    right_height = get_height(root_node.right_son, depth + 1)

    return max(left_height, right_height)


def balanced(root_node, height):
    if root_node == None:
        return True

    result_height = abs(
        get_height(root_node.left_son, height) -
        get_height(root_node.right_son, height))