From b2150d43045521ebdd211861d0b972e65eebf1aa Mon Sep 17 00:00:00 2001 From: ivan Date: Fri, 29 Nov 2024 04:30:33 -0600 Subject: [PATCH] adding path sum algo --- .../top_150_questions_round_11/path_sum.py | 21 +++++++++++++++++++ .../test_path_sum_round_11.py | 18 ++++++++++++++++ 2 files changed, 39 insertions(+) create mode 100644 src/my_project/interviews/top_150_questions_round_11/path_sum.py create mode 100644 tests/test_150_questions_round_11/test_path_sum_round_11.py diff --git a/src/my_project/interviews/top_150_questions_round_11/path_sum.py b/src/my_project/interviews/top_150_questions_round_11/path_sum.py new file mode 100644 index 00000000..63e1c924 --- /dev/null +++ b/src/my_project/interviews/top_150_questions_round_11/path_sum.py @@ -0,0 +1,21 @@ +from typing import List, Union, Collection, Mapping, Optional +from abc import ABC, abstractmethod + +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 + elif 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) \ No newline at end of file diff --git a/tests/test_150_questions_round_11/test_path_sum_round_11.py b/tests/test_150_questions_round_11/test_path_sum_round_11.py new file mode 100644 index 00000000..6428e8a6 --- /dev/null +++ b/tests/test_150_questions_round_11/test_path_sum_round_11.py @@ -0,0 +1,18 @@ +import unittest +from src.my_project.interviews.top_150_questions_round_11\ +.path_sum import TreeNode, Solution + + +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