-
Notifications
You must be signed in to change notification settings - Fork 257
Expand file tree
/
Copy pathleetcode 112 - path sum.py
More file actions
27 lines (19 loc) · 862 Bytes
/
leetcode 112 - path sum.py
File metadata and controls
27 lines (19 loc) · 862 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# path sum | leetcode 112 | https://leetcode.com/problems/path-sum/
# given the root of a tree, check if there exists a path whose sum equals target
# method: (dfs) update curSum for each node, and return true or false for each subtree
# 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, targetSum):
def dfs(root, curSum):
if root is None:
return False
curSum += root.val
if root.left is None and root.right is None:
return curSum == targetSum
return dfs(root.left, curSum) or dfs(root.right, curSum)
return dfs(root, 0)