From ae58d38b0937c7fd7c5fb3bb15c60102ac903bf1 Mon Sep 17 00:00:00 2001 From: ivan Date: Tue, 14 Oct 2025 03:44:34 -0600 Subject: [PATCH] adding algo --- .../top_150_questions_round_20/path_sum.py | 22 +++++++++++++++++++ .../test_path_sum_round_20.py | 17 ++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_20/path_sum.py create mode 100644 tests/test_150_questions_round_20/test_path_sum_round_20.py diff --git a/src/my_project/interviews/top_150_questions_round_20/path_sum.py b/src/my_project/interviews/top_150_questions_round_20/path_sum.py new file mode 100644 index 00000000..d2b8753b --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_20/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: + targetSum = targetSum - root.val + return self.hasPathSum(root.left, targetSum) \ + or self.hasPathSum(root.right, targetSum) \ No newline at end of file diff --git a/tests/test_150_questions_round_20/test_path_sum_round_20.py b/tests/test_150_questions_round_20/test_path_sum_round_20.py new file mode 100644 index 00000000..71dc2add --- /dev/null +++ b/tests/test_150_questions_round_20/test_path_sum_round_20.py @@ -0,0 +1,17 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_20\ +.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