-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path112.py
More file actions
24 lines (22 loc) · 718 Bytes
/
112.py
File metadata and controls
24 lines (22 loc) · 718 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
# Definition for a binary tree node.
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def hasPathSum(self, root: TreeNode, sum: int) -> bool:
if not root:
return False
nodes = [(0, root)]
while nodes:
parent_num, node = nodes.pop()
if not node:
continue
if (cur_num := node.val + parent_num) == sum and not node.left and not node.right:
return True
if node.left:
nodes.append((cur_num, node.left))
if node.right:
nodes.append((cur_num, node.right))
return False