user2375245
user2375245

Reputation: 45

Calculating height of a binary tree

I tried to implement a method to calculate height of a binary tree by creating a method internal to the binary tree class. It is showing the error None Type object doesn't have attribute height. here is the code:

def height(self):
    if self==None:
        return 0
    else :

            lheight=self.leftChild.height() 

            rheight=self.rightChild.height() 

            if lheight>rheight:
                return lheight+1
            else:
                return rheight+1

Upvotes: 0

Views: 270

Answers (1)

Neo
Neo

Reputation: 3786

Problem is that you dont check if right or left are None...
For every node before you set lheight and rheight check first that they are not None

if self.right is not None:
    rheight = self.right.height()

They don't check it theirselves because they just don't call height() - None Type has no height() function, the error stands there

Upvotes: 1

Related Questions