Recursion: return value vs. instance variable

  • 0

    Which solution would interviewers prefer to see?

    Return value approach:

    class Solution(object):
        def sumOfLeftLeaves(self, root):
            if not root: return 0
            if root.left and not root.left.left and not root.left.right:
                return root.left.val + self.sumOfLeftLeaves(root.right)
            return self.sumOfLeftLeaves(root.left) + self.sumOfLeftLeaves(root.right)

    Instance variable approach:

    class Solution(object):
        lsum = 0
        def sumOfLeftLeaves(self, root):
            :type root: TreeNode
            :rtype: int
            if not root:
                return 0
            return self.lsum
        def helper(self, root):
            if root.left:
                if not root.left.left and not root.left.right:
                    self.lsum += root.left.val
            if root.right: 

    For me, the instance variable approach is easier, but maybe the interviewer thinks it's almost cheating.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.