one line of code at a time
[leetcode] 112. Path Sum 파이썬 코드 본문
https://leetcode.com/problems/path-sum/description/
루트노드부터 단말노드까지 노드의 val 값을 더했을 때 targetSum과 같아지는 path가 있으면 true, 없으면 false를 반환하는 문제이다.
class Solution(object):
def hasPathSum(self, root, targetSum):
def dfs(root, curr_sum):
if not root:
return False
curr_sum += root.val
if not root.left and not root.right:
return curr_sum == targetSum
return dfs(root.left, curr_sum) or dfs(root.right, curr_sum)
return dfs(root, 0)

'leetcode' 카테고리의 다른 글
| [leetcode] 547. Number of Provinces 파이썬 코드 (0) | 2024.08.18 |
|---|---|
| [leetcode] 113. Path Sum II 파이썬 코드 (0) | 2024.08.17 |
| [leetcode] 1448. Count Good Nodes in Binary Tree 파이썬 코드 (0) | 2024.08.16 |
| [leetcode] 872. Leaf-Similar Trees 파이썬 코드 (0) | 2024.08.16 |
| [leetcode] 1161. Maximum Level Sum of a Binary Tree 파이썬 코드 (0) | 2024.08.16 |