본문 바로가기

카테고리 없음

7/20 코테 일지 (Helper 함수)

1. Helper 함수

https://leetcode.com/problems/path-sum/description/

Class 내 정의된 nested 함수를 helper 함수라고 부른다. 이 helper 함수는 클래스 내에서만 사용되는 보조적인 역할을 하며, 주로 클래스의 메서드들이 수행해야 하는 반복적인 작업을 분리하여 코드의 가독성을 높이고, 중복을 줄이기 위해 사용된다.

밑의 코드는 내가 짠 코드이며 helper 함수를 사용하지 않는다.

class Solution(object):
    def hasPathSum(self, root, targetSum,sum =0):
        if not root:
            return False
        sum += root.val

        if not root.left and not root.right:
            if sum ==targetSum:
                    return True
        if self.hasPathSum(root.left, targetSum , sum):
            return True
        if self.hasPathSum(root.right, targetSum, sum):
            return True
 
        sum -= root.val

        return False

밑의 코드는 예시 코드로 helper 함수를 사용한다. hasPathSum 자체를 재귀적으로 호출하지 않고 그 안의 helper함수를 재귀적으로 호출함으로써 코드가 훨씬 간결해졌다. 

class Solution(object):
    def hasPathSum(self, root, targetSum):
        """
        :type root: TreeNode
        :type targetSum: int
        :rtype: bool
        """
        
        def helper(root, count):
            if not root:
                return 0
            if not root.left and not root.right:
                if count + root.val == targetSum:
                    return True
                else:
                    return False
            return  helper(root.left, count+root.val) or helper(root.right, count+root.val)
            

        return helper(root, 0)