-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path112.path-sum.py
35 lines (31 loc) · 932 Bytes
/
112.path-sum.py
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
27
28
29
30
31
32
33
34
35
#
# @lc app=leetcode id=112 lang=python3
#
# [112] Path Sum
#
# @lc code=start
# 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
from collections import deque
queue = deque([root])
while len(queue) > 0:
node = queue.popleft()
if node.left is None and node.right is None:
if node.val == targetSum:
return True
if node.left:
node.left.val += node.val
queue.append(node.left)
if node.right:
node.right.val += node.val
queue.append(node.right)
return False
# @lc code=end