Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 9689153

Browse files
Path Sum
1 parent b716f53 commit 9689153

File tree

1 file changed

+47
-0
lines changed

1 file changed

+47
-0
lines changed

‎112-path-sum.py

Lines changed: 47 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,47 @@
1+
"""
2+
Problem Link: https://leetcode.com/problems/path-sum/
3+
4+
Given the root of a binary tree and an integer targetSum,
5+
return true if the tree has a root-to-leaf path such that adding up all
6+
the values along the path equals targetSum.
7+
A leaf is a node with no children.
8+
9+
Example 1:
10+
Input: root = [5,4,8,11,null,13,4,7,2,null,null,null,1], targetSum = 22
11+
Output: true
12+
Explanation: The root-to-leaf path with the target sum is shown.
13+
14+
Example 2:
15+
Input: root = [1,2,3], targetSum = 5
16+
Output: false
17+
Explanation: There two root-to-leaf paths in the tree:
18+
(1 --> 2): The sum is 3.
19+
(1 --> 3): The sum is 4.
20+
There is no root-to-leaf path with sum = 5.
21+
22+
Example 3:
23+
Input: root = [], targetSum = 0
24+
Output: false
25+
Explanation: Since the tree is empty, there are no root-to-leaf paths.
26+
27+
Constraints:
28+
The number of nodes in the tree is in the range [0, 5000].
29+
-1000 <= Node.val <= 1000
30+
-1000 <= targetSum <= 1000
31+
"""
32+
# Definition for a binary tree node.
33+
# class TreeNode:
34+
# def __init__(self, val=0, left=None, right=None):
35+
# self.val = val
36+
# self.left = left
37+
# self.right = right
38+
class Solution:
39+
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
40+
if not root:
41+
return False
42+
43+
if targetSum - root.val == 0 and not root.left and not root.right:
44+
return True
45+
46+
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
47+

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /