def generate_random_tree(a, b, c):
    my_set = []
    tree = None
    while len(my_set) < c:
        num = random.randint(a, b)
        if num not in my_set:
            my_set.append(num)
            if tree is None:
                tree = Tree(num)
            else:
                tree.insert(Tree(num))
    print('list', my_set, '\n')
    return tree
def test_delete():
    my_list = []
    my_list.append(2)
    my_list.append(1)
    my_list.append(7)
    my_list.append(4)
    my_list.append(8)
    my_list.append(3)
    my_list.append(6)
    my_list.append(5)

    tree = Tree(2)
    tree.insert(Tree(1))
    tree.insert(Tree(7))
    tree.insert(Tree(4))
    tree.insert(Tree(8))
    tree.insert(Tree(3))
    tree.insert(Tree(6))
    tree.insert(Tree(5))

    print('list', my_list, '\n')
    print('delete node 7:')
    tree.delete(7)
    tree.print()
    print('delete node 5:')
    tree.delete(5)
    tree.print()
Пример #3
0
    if len(n1_path) == 0 or len(n2_path) == 0:
        return None

    print(n1_path, n2_path)
    for p in n1_path:
        if p in n2_path:
            return p


# populate tree
# this will take a very long time since inserting to n-ary tree will do a search then insert O(n)
for i in nodes:
    path = getPath(i)
    path.reverse()
    print(len(nodes) - int(i))
    for node in path:
        tree.insert(nodes[node].tax_id, nodes[node].parent_id,
                    nodes[node].rank)

# ask for input for calling lca
# change find_lca to find_lca2 for using tree implementation instead of dictionary
while True:
    input1 = input('Enter first node tax_id (enter q to exit): ')
    if input1.lower() == 'q':
        break
    input2 = input('Enter second node tax_id (enter q to exit): ')
    if input2.lower() == 'q':
        break
    res = find_lca(input1, input2)
    print('The lowest common ancestor of', input1, 'and', input2, 'is', res)
Пример #4
0
from classes.tree import TreeNode, Tree

tree = Tree()
tree.insert(1)
tree.insert(3, 1)
tree.insert(2, 1)
tree.insert(4, 2)
tree.insert(7, 2)
tree.insert(78, 7)
tree.insert(10, 3)
tree.insert(10, 3)

print(tree.print(tree.root, ''))

def find_lca(tree, n1, n2):
    _, n1_path = tree.search(tree.root, n1)
    _, n2_path = tree.search(tree.root, n2)
    if n1_path is None:
        print('Node ', n1, ' doesn\'t exist')
        return None

    if n2_path is None:
        print('Node ', n2, ' doesn\'t exist')
        return None

    n1_path = n1_path.split(',')
    n2_path = n2_path.split(',')

    if len(n1_path) == 0 or len(n2_path) == 0:
        return None