【问题标题】:Height of Binary Tree?二叉树的高度?
【发布时间】:2018-07-25 17:29:22
【问题描述】:

我正在尝试实现一种递归方法来计算二叉树的高度。这是“高度”的代码:

def HeightOfTree(self):
    if self.root is None:
        return 0
    else:
        ans=self._HeightOfTree(self.root)
        return ans

def _HeightOfTree(self,currentNode):
    if currentNode.hasleftChild():
        lheight=1+self._HeightOfTree(currentNode.leftChild)
    if currentNode.hasrightChild():
        rheight=1+self._HeightOfTree(currentNode.rightChild)
    if lheight > rheight:
        return (lheight+1)
    else:
        return (rheight+1)

当我尝试调用该函数时,我收到以下错误消息:

UnboundLocalError: local variable 'lheight' referenced before assignment   

我该如何解决这个问题?

【问题讨论】:

  • 你的树是什么单节点? lheightrheight 都没有值。
  • 附注:无论何时使用递归,都需要有一个基本情况。否则,函数将永远不会结束(或者会崩溃)。

标签: python python-3.x recursion tree


【解决方案1】:

如果您在 if 块中设置变量的值并且稍后尝试使用它,请确保它在块之前声明,以便如果 if 没有发生,它仍然存在.

错误:

if False:
    x = 3
print(x)
# UnboundLocalError

对:

x = 0
if False:
    x = 3
print(x)
# 0

【讨论】:

    【解决方案2】:

    您将获得UnboundLocalError,因为在leftChildrightChildNone 的情况下不会创建值rheightlheight

    如果您定义_HeightOfTree(None) == 0 的基本情况会更简单:

    def _HeightOfTree(self,currentNode):
        if currentNode is None:
            return 0
        return 1 + max(self._HeightOfTree(currentNode.leftChild), self._HeightOfTree(currentNode.rightChild))
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多