【问题标题】:Find closest value in a Binary Search Tree - Python在二叉搜索树中查找最接近的值 - Python
【发布时间】:2021-01-28 05:10:07
【问题描述】:

我的代码在下面创建一个二叉搜索树,然后使用递归方法返回最接近的值。当我在调试模式下运行它时,我可以看到它在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, target, closestValue)

    def closest_helper(self, currentNode, target, 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, target, closestValue)
        elif target > currentNode.value:
            return self.closest_helper(currentNode.right, target, 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 in findClosestValueInBST...
  • 这行得通。谢谢

标签: python-3.x algorithm recursion data-structures binary-search-tree


【解决方案1】:

只需在函数中添加 return 即可。由于你还没有返回任何东西,终端打印None

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

【讨论】:

    猜你喜欢
    • 2021-12-28
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-12-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多