Skip to content

Commit a0cc2e6

Browse files
authored
Merge pull request #1107 from ivan1016017/november29
adding path sum algo
2 parents eb794d8 + b2150d4 commit a0cc2e6

File tree

2 files changed

+39
-0
lines changed

2 files changed

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

0 commit comments

Comments
 (0)