根据指定的键查找BST的深度


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 += 1
depthCount = myMagicFunction()

这段代码看起来有点奇怪——第一行基本上没有效果,因为depthCount在下一行被覆盖。

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

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

希望这能有所帮助!

最新更新