【问题标题】:Finding the depth of a BST base on the key specified根据指定的键查找 BST 的深度
【发布时间】:2020-03-13 14:41:35
【问题描述】:
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

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

【问题讨论】:

    标签: python recursion binary-search-tree


    【解决方案1】:

    看看这些代码行:

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

    让我们暂时搁置这段代码是递归的事实。想象一下我写了这段代码:

    depthCount += 1
    depthCount = myMagicFunction()
    

    这段代码看起来有点奇怪 - 第一行基本上没有任何作用,因为depthCount 在下一行被覆盖。

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

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-12-15
      • 1970-01-01
      • 1970-01-01
      • 2022-10-14
      • 2021-12-02
      • 1970-01-01
      • 2013-11-26
      • 1970-01-01
      相关资源
      最近更新 更多