From cef4a48ca9f66bf197dede44735bab88020a94c4 Mon Sep 17 00:00:00 2001 From: ktkovachev <143198904+ktkovachev@users.noreply.github.com> Date: Mon, 8 Apr 2024 18:18:54 +0100 Subject: [PATCH] Solve 112. Path Sum --- python/112_path_sum.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 python/112_path_sum.py diff --git a/python/112_path_sum.py b/python/112_path_sum.py new file mode 100644 index 0000000..8335cbc --- /dev/null +++ b/python/112_path_sum.py @@ -0,0 +1,17 @@ +# 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: Optional[TreeNode], targetSum: int) -> bool: + def hasPathSumInner(root: Optional[TreeNode], currentSum: int) -> bool: + if root is None: + return False + elif root.left is None and root.right is None: + return currentSum + root.val == targetSum + else: + newSum = currentSum + root.val + return hasPathSumInner(root.left, newSum) or hasPathSumInner(root.right, newSum) + return hasPathSumInner(root, 0)