Skip to content

Commit 9326620

Browse files
committed
adding path sum
1 parent 6abb30e commit 9326620

2 files changed

Lines changed: 40 additions & 0 deletions

File tree

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,23 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
5+
class TreeNode:
6+
def __init__(self, val=0, left=None, right=None):
7+
self.val = val
8+
self.left = left
9+
self.right = right
10+
11+
12+
class Solution:
13+
14+
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
15+
16+
if not root:
17+
return False
18+
elif not root.left and not root.right and root.val == targetSum:
19+
return True
20+
else:
21+
temp_target = targetSum - root.val
22+
return self.hasPathSum(root.left, temp_target) \
23+
or self.hasPathSum(root.right, temp_target)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import unittest
2+
from src.my_project.interviews.top_150_questions_round_12\
3+
.path_sum import Solution, TreeNode
4+
5+
class HasPathSumTestCase(unittest.TestCase):
6+
7+
def test_is_path_sum(self):
8+
solution = Solution()
9+
tree = TreeNode(1, TreeNode(2), TreeNode(3))
10+
output = solution.hasPathSum(root=tree, targetSum=3)
11+
self.assertTrue(output)
12+
13+
def test_is_no_path_sum(self):
14+
solution = Solution()
15+
tree = TreeNode(1, TreeNode(2), TreeNode(3))
16+
output = solution.hasPathSum(root=tree, targetSum=10)
17+
self.assertFalse(output)

0 commit comments

Comments
 (0)