Python递归和返回语句

imi*_*ric 17 python recursion

我对Python和整个递归函数都很陌生,所以请原谅我的无知.

我试图在Python中实现二进制搜索树并具有以下插入方法(从类中取出):

def insert(self, key, root=None):
    '''Inserts a node in the tree'''
    if root == None:
        root = self.root
    if root.key == None:
        self._update(root, key)
        return 0
    else:
        tmp = root
        if key > tmp.key: # we work with the right subtree
            self.insert(key, root=tmp.right)
        elif key < tmp.key: # we work with the left subtree
            self.insert(key, root=tmp.left)
        else: # key already exists
            return 0
Run Code Online (Sandbox Code Playgroud)

我不确定这是否清晰,但是它会遍历树,直到它达到None值并使用要插入的键更新节点.

现在,该方法可以正常工作并从头开始正确创建BST.但是返回语句存在问题,因为如果没有执行递归,它只返回0.

>>> bst.insert(10)
0
>>> bst.insert(15)
>>> bst.root.right.key
15
>>>
Run Code Online (Sandbox Code Playgroud)

"插入"根键再次返回0(从第15行)它应该的方式.

>>> bst.insert(10)
0
Run Code Online (Sandbox Code Playgroud)

我无法弄清楚为什么会这样.如果我在第6行放置一个print语句,它会正确执行,但它不会在第一次插入后返回任何内容.为什么是这样?(我很确定我遗漏了一些关于Python和递归的基本信息)

谢谢你的帮助,

伊万

PS:我已经知道递归并不是实现BST的最佳方式,所以我会研究其他解决方案,但在继续之前我想知道答案.

Nat*_*ath 24

在递归线上,您不返回任何内容.如果你想让它返回0,你应该用以下行替换它们:

return self.insert(key, root=tmp.left)
Run Code Online (Sandbox Code Playgroud)

而不仅仅是

self.insert(key, root=tmp.left)
Run Code Online (Sandbox Code Playgroud)


Das*_*Ich 18

你在函数内部想要返回一个值,你做什么?你写

def function():
    return value
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您希望返回函数调用返回的值,因此您必须这样做.

def function():
    return another_function()
Run Code Online (Sandbox Code Playgroud)

但是你这样做

def function():
    another_function()
Run Code Online (Sandbox Code Playgroud)

为什么你认为这应该有效?当然你使用递归但是在这种情况下你应该记住Python的Zen,它简单地说:

特殊情况不足以打破规则.