5

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

def height(self):
    if self.root==None:
        return 0
    return max(height(self.root.left), height(self.root.right))+1

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

NameError: name 'height' is not defined

Does anybody see the problem?

2 Answers 2

8

This is a method of your class, hence you must call it from an instance (self) or the class itself. Though it won't work as you think, unless you define it as a staticmethod or change your call, e.g.

def height(self):
    return 1 + max(self.left.height() if self.left is not None else 0, 
                   self.right.height() if self.right is not None else 0) 

or

@staticmethod
def height(self):
    return 1 + max(self.height(self.left) if self.left is not None else 0,
                   self.height(self.right) if self.right is not None else 0)

Notice, that you shouldn't use == to compare with None (kudos to timgeb). And you must check whether child-nodes exist, too. And your algorithm doesn't work, so I've changed it slightly.

Example:

class Node:
    def __init__(self, root=None, left=None, right=None):
        self.root = root
        self.left = left
        self.right = right

    def height(self):
        return 1 + max(self.left.height() if self.left is not None else 0, 
                       self.right.height() if self.right is not None else 0)


# Create a binary tree of height 4 using the binary-heap property
tree = [Node() for _ in range(10)]
root = tree[0]

for i in range(len(tree)):
    l_child_idx, r_child_idx = (i + 1) * 2 - 1, (i + 1) * 2
    root_idx = (i + 1) // 2
    if root_idx: 
        tree[i].root = tree[root_idx]
    if l_child_idx < len(tree):
        tree[i].left = tree[l_child_idx]
    if r_child_idx < len(tree):
        tree[i].right = tree[r_child_idx]

print(root.height())  # -> 4
Sign up to request clarification or add additional context in comments.

10 Comments

You should also replace self.root==None with self.root is None.
I'm not sure I follow. Neither in Python2 nor 3 you'll get an error checking for None this way.
@timgeb Oh, sorry, I thought they made an error out of it in Python 3. I'm using Python 2 most of the time, so sorry for the misconception.
Now I get the error msg "'NoneType' object has no attribute 'height'". Shouldn't the base case prevent this?
@EliKorvigo Now I get the error msg "AttributeError: 'Treenode' object has no attribute 'height'". Of course height is a method to the class Bintree which in turn is creating nodes using the class Treenode but surely I shouldn't have to add a height method to Treenode??
|
0

I am not sure of how you define your binary tree. But on a tree node you usually have only one root and multiple sons. I have the feeling that this method leads to an infinite loop. self.root.left and self.root.right are exactly my brother and me...

Here you probably have to call the method from the instances self.root.left and self.root.right with no extra argument :

def height(self):
    if self.root==None:
        return 0
    return max(self.root.left.height(), self.root.right.height())+1

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.