Surya Kannan KMS
Surya Kannan KMS

Reputation: 41

Recursive Function: recursion with python

I have this Function:

def depth(self):
        if self.root == None:
            return 0
        left = depth(self.left)
        right = depth(self.right)
        if left>right:
            return left+1
        else:
            return right+1

But when I run it, the following error pops up:

 File "/Users/suryakannan/Documents/Python Programs/binaryTree.py", line 60, in depth
    left = depth(self.left)
NameError: name 'depth' is not defined

So, what should I do to fix this function?

Upvotes: 0

Views: 114

Answers (1)

prithajnath
prithajnath

Reputation: 2115

Since depth is an instance method, you need to use the self reference

def depth(self):
    if self.root == None:
        return 0
    left = self.depth(self.left)
    right = self.depth(self.right)
    if left>right:
        return left+1
    else:
        return right+1

Upvotes: 2

Related Questions