BST在Python中插入不正常

时间:2016-04-11 13:31:44

标签: python data-structures binary-search-tree implementation

我在Python中实现了BST,但我遇到了but_insert(t, k)的问题。 基本上,如果我只是将子项添加到根,如下所示,它可以工作:

T = Node(7)
bst_insert(T, 9)
bst_insert(T, 5)

但是如果我插入另一个密钥,则根目录中的整个分支似乎被删除。例如,如果我执行:

T = Node(7)
bst_insert(T, 9)
bst_insert(T, 5)
bst_insert(T, 3)

然后,当我按顺序打印T时,我才会获得7 9

以下是Node构造函数和bst_insertprint_in_order函数正常工作,所以我没有包含它。)

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None


def bst_insert(t, k):
    if t is None:
        t = Node(k)

    elif k <= t.key:
        if t.left is None:
            t.left = Node(k)
        else:
            t.left = bst_insert(t.left, k)
    else:
        if t.right is None:
            t.right = Node(k)
        else:
            t.right = bst_insert(t.right, k)

感谢。

1 个答案:

答案 0 :(得分:0)

    class Node:
        def __init__(self, key):
            self.key = key
            self.left = None
            self.right = None


    def bst_insert(t, k):
        if t is None:
            t = Node(k)

        elif k <= t.key:
            if t.left is None:
                t.left = Node(k)
            else:
                t.left = bst_insert(t.left, k) #1
        else:
            if t.right is None:
                t.right = Node(k)
            else:
                t.right = bst_insert(t.right, k) #2
        # return the node, #1 and #2 will always get None value
        return t