0

I'm trying to implement a recursive method to calculate the height of a binary tree. Here is the "height"-code:

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)

When I try to call the function, I get the following error msg:

UnboundLocalError: local variable 'lheight' referenced before assignment   

How can I fix this problem ?

2 Answers2

3

If you're setting the value of a variable in an if block and you try to use it later, make sure that it's declared before the block so that if the if doesn't happen, it still exists.

Wrong:

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

Right:

x = 0
if False:
    x = 3
print(x)
# 0
MoxieBall
  • 1,907
  • 7
  • 23
0

You are getting the UnboundLocalError because the values rheight and lheight are not created in the case that leftChild or rightChild are None.

It would be simpler if you defined a base case of _HeightOfTree(None) == 0:

def _HeightOfTree(self,currentNode):
    if currentNode is None:
        return 0
    return 1 + max(self._HeightOfTree(currentNode.leftChild), self._HeightOfTree(currentNode.rightChild))
Ben Jones
  • 652
  • 6
  • 21