From 57f1010b027052fbbd79ee724bdef118a37dd203 Mon Sep 17 00:00:00 2001 From: ivan Date: Mon, 8 Sep 2025 04:29:50 -0600 Subject: [PATCH] adding algo --- .../top_150_questions_round_19/path_sum.py | 22 +++++++++++++++++++ .../test_path_sum_round_19.py | 17 ++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_19/path_sum.py create mode 100644 tests/test_150_questions_round_19/test_path_sum_round_19.py diff --git a/src/my_project/interviews/top_150_questions_round_19/path_sum.py b/src/my_project/interviews/top_150_questions_round_19/path_sum.py new file mode 100644 index 00000000..c108f88a --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_19/path_sum.py @@ -0,0 +1,22 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +# Definition for a binary tree node. +class TreeNode: + def __init__(self, val=0, left=None, right=None): + self.val = val + self.left = left + self.right = right + +class Solution: + + def hasPathSum(self, root: TreeNode, targetSum: int) -> bool: + + if not root: + return False + if not root.left and not root.right and root.val == targetSum: + return True + else: + temp_target = targetSum - root.val + return self.hasPathSum(root.left, temp_target) \ + or self.hasPathSum(root.right, temp_target) diff --git a/tests/test_150_questions_round_19/test_path_sum_round_19.py b/tests/test_150_questions_round_19/test_path_sum_round_19.py new file mode 100644 index 00000000..5e58bad2 --- /dev/null +++ b/tests/test_150_questions_round_19/test_path_sum_round_19.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_19\ +.path_sum import Solution, TreeNode + +class HasPathSumTestCase(unittest.TestCase): + + def test_is_path_sum(self): + solution = Solution() + tree = TreeNode(1, TreeNode(2), TreeNode(3)) + output = solution.hasPathSum(root=tree, targetSum=3) + self.assertTrue(output) + + def test_is_no_path_sum(self): + solution = Solution() + tree = TreeNode(1, TreeNode(2), TreeNode(3)) + output = solution.hasPathSum(root=tree, targetSum=10) + self.assertFalse(output) \ No newline at end of file