微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在二进制搜索树中查找最接近的值-Python

如何解决在二进制搜索树中查找最接近的值-Python

下面的代码创建了一个二叉搜索树,然后使用递归方法返回最接近的值。当我在调试模式下运行此命令时,我可以看到它在closestValue中存储了正确的值,但是终端会显示None

我需要编辑什么代码行才能返回正确的值?

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

class BST:
    def __init__(self):
        self.head = None

    def insert(self,value):
        n = Node(value)
        if self.head == None:
            self.head = n
            return
        else:
            parent = self.head
            while parent != None:
                if parent.value < n.value:
                    if parent.right == None:
                        parent.right = n
                        break
                    else:
                        parent = parent.right

                elif parent.value > n.value:
                    if parent.left == None:
                        parent.left = n
                        break
                else:
                    parent = parent.left

            else:
                pass


    def findClosestValueInBST(self,target,closestValue):
        currentNode = self.head
        self.closest_helper(currentNode,closestValue)

    def closest_helper(self,currentNode,closestValue):
        if currentNode == None:
            return closestValue

        if abs(target - closestValue) > abs(target - currentNode.value):
            closestValue = currentNode.value
        if target < currentNode.value:
            return self.closest_helper(currentNode.left,closestValue)
        elif target > currentNode.value:
            return self.closest_helper(currentNode.right,closestValue)
    else:
        return closestValue


array = [10,5,15,2,7,13,22]
bst = BST()
for num in array:
    bst.insert(num)


print(bst.findClosestValueInBST(23,100))

解决方法

只需在函数中添加return。由于您还没有退货,因此终端会显示None

def findClosestValueInBST(self,target,closestValue):
        currentNode = self.head
        return self.closest_helper(currentNode,closestValue)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。