Skip to content

Commit 5e52286

Browse files
authored
Merge pull request #1424 from ivan1016017/october14
adding algo
2 parents af0068a + ae58d38 commit 5e52286

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed
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+
targetSum = targetSum - root.val
21+
return self.hasPathSum(root.left, targetSum) \
22+
or self.hasPathSum(root.right, targetSum)
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_20\
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)