二叉树的高度?

时间:2018-07-25 17:29:23

标签: python python-3.x recursion tree

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

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   

如何解决此问题?

2 个答案:

答案 0 :(得分:3)

如果您要在if块中设置变量的值,并在以后尝试使用它,请确保在该块之前声明了该变量的值,这样就不会发生if ,它仍然存在。

错误:

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

右:

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

答案 1 :(得分:0)

您得到UnboundLocalError是因为在rheightlheightleftChild的情况下未创建值rightChildNone

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

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