简体   繁体   中英

inserting value to a binary tree but produces none value

def build_tree(entry, left, right):
    return [entry, left, right]

def entry(tree):
    return tree[0]

def left_branch(tree):
    return tree[1]

def right_branch(tree):
    return tree[2]

def make_empty_tree():
    return []

t1 = build_tree(2,build_tree(1,make_empty_tree(),make_empty_tree()),build_tree(3,make_empty_tree(),make_empty_tree()))

These are the functions that I have currently defined for the binary tree. i wish to insert a value to the right branch of T1 using the following function.

def insert_tree(x, tree):
    if tree == []: 
        tree.append(x)
        return tree
    else:
        if x <= entry(tree): 
            return insert_tree(x , left_branch(tree))
        else: 
            return insert_tree(x , right_branch(tree))

however, this gives me [5] instead of the expected [2, [[1],[],[]], [[3],[],[5]] .

I am guessing that you call t1 = insert_tree(t1, 5) ? The problem is that insert_tree only returns in the special case of the argument tree == [] . Return the tree at the end instead.

def insert_tree(x, tree):
    if tree == []: 
        tree.append(x)
    else:
        if x <= entry(tree): 
            insert_tree(x , left_branch(tree))
        else: 
            insert_tree(x , right_branch(tree))
    return tree

Btw, your functions does not constitute a valid definition of a tree, for example left_branch(make_empty_tree()) would fail.

If you call insert_tree with:

insert_tree(5, t1)

then t1 would become:

[2, [1, [], []], [3, [], [5]]]

but this is not a well-formed tree because the tree of 5 should have two empty child nodes as well. You should instead initialize the tree by extending the list with an additional two empty lists:

def insert_tree(x, tree):
    if tree == []:
        tree.extend([x, [], []])
        return tree
    if x <= entry(tree):
        return insert_tree(x , left_branch(tree))
    else:
        return insert_tree(x , right_branch(tree))

so that insert_tree(5, t1) would make t1 :

[2, [1, [], []], [3, [], [5, [], []]]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM