Elliot Doubleday
Elliot Doubleday

Reputation: 11

Height of Binary Tree?

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 ?

Upvotes: 0

Views: 87

Answers (2)

Ben Jones
Ben Jones

Reputation: 629

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))

Upvotes: 0

MoxieBall
MoxieBall

Reputation: 1916

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

Upvotes: 3

Related Questions