简体   繁体   English

将值插入二叉树但不产生值

[英]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. 我希望使用以下函数在T1的右分支中插入一个值。

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]] . 但是,这给了我[5]而不是预期的[2, [[1],[],[]], [[3],[],[5]]

I am guessing that you call t1 = insert_tree(t1, 5) ? 我猜你叫t1 = insert_tree(t1, 5) The problem is that insert_tree only returns in the special case of the argument tree == [] . 问题是insert_tree仅在参数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. 顺便说一句,您的函数未构成树的有效定义,例如left_branch(make_empty_tree())将会失败。

If you call insert_tree with: 如果使用以下命令调用insert_tree

insert_tree(5, t1)

then t1 would become: 那么t1将变为:

[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. 但这不是一棵格式正确的树,因为5棵树也应该有两个空子节点。 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 : 这样insert_tree(5, t1)将成为t1

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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