[Python] 112. Path Sum

정지은·2022년 10월 4일
0

코딩문제

목록 보기
4/25

112. Path Sum

문제

Given the root of a binary tree and an integer targetSum, return true if the tree has a root-to-leaf path such that adding up all the values along the path equals targetSum.

A leaf is a node with no children.

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

접근

#DFS #이진트리 #연결리스트

깊이우선탐색으로 모든 루트를 방문한 뒤, 최종 합계가 targetSum과 같으면 True를 리턴한다.

코드

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
        def dfs(node, s):
    
            s += node.val
            
            if node.left is None and node.right is None:
                if s == targetSum:
                    return True
            
            l, r = False, False
            
            if node.left is not None:
                l = dfs(node.left, s)
            if node.right is not None:
                r = dfs(node.right, s)
                
            #좌측 노드와 우측 노드 중 하나라도 targetSum을 만족하면 True를 리턴한다.
            return l or r 
        
        if root is None:
            return False
        
        return dfs(root, 0)

        

효율성

Runtime: 89 ms, faster than 26.85% of Python3 online submissions for Path Sum.
Memory Usage: 15 MB, less than 91.98% of Python3 online submissions for Path Sum.

profile
Steady!

0개의 댓글