-1

I want to define a 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 and root.left.right == None):
      return root.left.val + sumOfLeftLeaves(root.right)
    else:
      return sumOfLeftLeaves(root.left)+sumOfLeftLeaves(root.right)

But it gives an error "NameError: global name 'sumOfLeftLeaves' is not defined", but I think it's defined recursively, what's wrong?

CYC
  • 619
  • 1
  • 5
  • 13
  • As an aside, why the `Solution` class? Is this required for some online submission format? A class with a single method and no internal state should probably not be a class at all, and just a module-level function... – juanpa.arrivillaga Sep 11 '17 at 19:35

1 Answers1

2

sumOfLeftLeaves is still a method on the class and not a globally defined function. You can access it as bound method on self, just like you'd access any other method:

self.sumOfLeftLeaves(...)

You should really use is None when testing for the None object as well:

class Solution(object):
    def sumOfLeftLeaves(self, root):
        if root.val is None:
            return 0
        elif (root.left.left is None and root.left.right is None):
            return root.left.val + self.sumOfLeftLeaves(root.right)
        else:
            return (self.sumOfLeftLeaves(root.left) + 
                    self.sumOfLeftLeaves(root.right))
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343