Recursion: return value vs. instance variable


  • 0
    B

    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
            
            self.helper(root)
            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
                else:
                    self.helper(root.left)
            
            if root.right: 
                self.helper(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.