为什么搜索功能返回无?

时间:2017-12-15 01:27:52

标签: python binary-search-tree

作为一项功课,我必须从给定的数组构建一个二进制搜索树,并在其上面创建一些函数。 search()函数不起作用,我不知道为什么,它会一直返回None,即使它应该返回TrueFalse。 我的代码在构建函数时可能存在错误,但上传系统会写入,它成功构建了一个树。

visited = 0

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


class BinarySearchTree:
    def __init__(self):
        self.root = None

    def insert(self, value):
        if self.root is None:
            self.root = Node(value)
        else:
            self._insert(value, self.root)

    def _insert(self, value, curNode):
        if value < curNode.data:
            if curNode.left is None:
                curNode.left = Node(value)
            else:
                self._insert(value, curNode.left)
        else:
            if curNode.right is None:
                curNode.right = Node(value)
            else:
                self._insert(value, curNode.right)

    def fromArray(self, array):
        for i in range(len(array) - 1):
            value = array[i]
            self.insert(value)
            i += 1

    def search(self, value):
        global visited
        if self.root.data is None:
            visited += 1
            return False
        else:
            return self._search(value, self.root)

    def _search(self, value, curNode):
        global visited
        if value == curNode.data:
            visited += 1
            return True
        elif value < curNode.data and curNode.left is not None:
            self._search(value, curNode.left)
        elif value > curNode.data and curNode.right is not None:
            self._search(value, curNode.right)
        else:
            return False

    def min(self):
        global visited
        curNode = self.root
        while curNode.left is not None:
            visited += 1
            curNode = curNode.left
        return curNode

    def max(self):
        global visited
        curNode = self.root
        while curNode.right is not None:
            visited += 1
            curNode = curNode.right
        return curNode

    def visitedNodes(self):
        return visited

1 个答案:

答案 0 :(得分:3)

检查_search()功能。它不会在第二个或第三个测试用例中返回任何内容。如果未在python中明确定义return,则该方法返回None

修复可能是

def _search(self, value, curNode):
    global visited
    if value == curNode.data:
        visited += 1
        return True
    elif value < curNode.data and curNode.left is not None:
        return self._search(value, curNode.left)
    elif value > curNode.data and curNode.right is not None:
        return self._search(value, curNode.right)
    else:
        return False