How to define function in class properly in Python? -
this question has answer here:
i want define function sumofleftleaves recursively:
class node(object): def __init__(self,x): self.val = x self.left = none self.right = none class solution(object): def sumofleftleaves(self,root): if root.val == none: return 0 elif (root.left.left == none , root.left.right == none): return root.left.val + sumofleftleaves(root.right) else: return sumofleftleaves(root.left)+sumofleftleaves(root.right)
but gives error "nameerror: global name 'sumofleftleaves' not defined", think it's defined recursively, what's wrong?
sumofleftleaves
still method on class , not globally defined function. can access bound method on self
, you'd access other method:
self.sumofleftleaves(...)
you should use is none
when testing none
object well:
class solution(object): def sumofleftleaves(self, root): if root.val none: return 0 elif (root.left.left none , root.left.right none): return root.left.val + self.sumofleftleaves(root.right) else: return (self.sumofleftleaves(root.left) + self.sumofleftleaves(root.right))
Comments
Post a Comment