为什么我的Python递归函数返回“ none”而不是“ True”?

时间:2019-12-12 11:58:49

标签: python recursion tree binary-search-tree nonetype

我创建了一个search函数,该函数应该在二叉树中找到一个值,如果找到该值,则返回True,如果找不到,则返回False

树是正确的,我已经测试过。

当我打印字符串"Found""Not found"时,不同的情况会起作用。但是return True不起作用。

这是我的Tree类的代码:

class Tree(object):

    def __init__(self):
        self.fg = None
        self.fd = None
        self.data = None

    def insert(self, data):
        if self.data == None:
            self.data = data

        elif self.data > data:
            if self.fg == None:
                self.fg = Tree()
            self.fg.insert(data)

        elif self.data < data:
            if self.fd == None:
                self.fd = Tree()
            self.fd.insert(data)

    def search(self, data):
        if self.data == None:
            return False
        elif self.data == data:
            print("Found")
            return True

        if self.data > data:
            if self.fg == None:
                return False
            else:
                self.fg.search(data)

        elif self.data < data:
            if self.fd == None:
                return False
            else:
                self.fd.search(data)

tree = Tree()

tree.insert(6)
tree.insert(3)
tree.insert(4)
tree.insert(5)

print(tree.search(6), "\n")
print(tree.search(7), "\n")
print(tree.search(3), "\n")
print(tree.search(4), "\n")
print(tree.search(5), "\n")

这是结果:

Found
True 

Not found
False 

Found
None 

Found
None 

Found
None

谢谢您的帮助。

1 个答案:

答案 0 :(得分:2)

您应该返回递归调用的值

return self.fg.search(data)