Skip to content

Commit 2dcec91

Browse files
authored
Merge pull request #1388 from ivan1016017/september08
adding algo
2 parents c7622ca + 57f1010 commit 2dcec91

2 files changed

Lines changed: 39 additions & 0 deletions

File tree

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
from typing import List, Union, Collection, Mapping, Optional
2+
from abc import ABC, abstractmethod
3+
4+
# Definition for a binary tree node.
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+
class Solution:
12+
13+
def hasPathSum(self, root: TreeNode, targetSum: int) -> bool:
14+
15+
if not root:
16+
return False
17+
if not root.left and not root.right and root.val == targetSum:
18+
return True
19+
else:
20+
temp_target = targetSum - root.val
21+
return self.hasPathSum(root.left, temp_target) \
22+
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_19\
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)