Python 在指定的键上查找BST基的深度 def深度(自身,按键): temp=自获取(键) 当前=自根 深度计数=0 如果temp为无: 一无所获 如果self.root.key为key: 返回0 如果current.keykey和(temp.left不是None): 当前=当前。左#键

Python 在指定的键上查找BST基的深度 def深度(自身,按键): temp=自获取(键) 当前=自根 深度计数=0 如果temp为无: 一无所获 如果self.root.key为key: 返回0 如果current.keykey和(temp.left不是None): 当前=当前。左#键,python,recursion,binary-search-tree,Python,Recursion,Binary Search Tree,您好,我正在尝试根据我给出的代码查找深度,但每当我尝试运行它时,它都只给出节点的高度,而不是深度。请查看以下代码行: def depth(self, key): temp = self.get(key) current = self.root depthCount = 0 if temp is None: return None if self.root.key is key: return 0 if curre

您好,我正在尝试根据我给出的代码查找深度,但每当我尝试运行它时,它都只给出节点的高度,而不是深度。

请查看以下代码行:

def depth(self, key):
    temp = self.get(key)
    current = self.root
    depthCount = 0
    if temp is None: 
        return None
    if self.root.key is key:  
       return 0
    if current.key < key and (temp.right is not None): 
        current = current.right
        depthCount += 1
        depthCount = self.depth(temp.right.key)
    if current.key > key and (temp.left is not None):
        current = current.left  # key < Root Key
        depthCount += 1
        depthCount = self.depth(temp.left.key)
    return depthCount
让我们暂时撇开这段代码是递归的这一事实不谈。想象一下,我写了以下代码:

depthCount += 1
depthCount = self.depth(temp.right.key)
这段代码看起来有点奇怪-第一行基本上没有效果,因为下一行中的
depthCount
正在被覆盖

如果您的目标是将
depthCount
设置为1加上通过调用递归函数得到的任何值,那么您可以编写如下代码:

depthCount += 1
depthCount = myMagicFunction()
希望这有帮助

depthCount = 1 + self.depth(temp.right.key)