-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112.Path-Sum.py
More file actions
25 lines (22 loc) · 877 Bytes
/
112.Path-Sum.py
File metadata and controls
25 lines (22 loc) · 877 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
# 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:
if not root:
return False
def backtracking(node, path_sum):
if not node.left and not node.right:
if path_sum == targetSum:
return True
else:
return False
if node.left:
if backtracking(node.left, path_sum + node.left.val): return True
if node.right:
if backtracking(node.right, path_sum + node.right.val): return True
return False
return backtracking(root, root.val)