The Path Sum solutions are below.
15 Jun 2024•Easy•C++ / Python / TypeScript
Path Sum
C++, Python and TypeScript solutions for Path Sum.
Solution files
Python•path-sum/synced-solution.py
class Solution:
def hasPathSum(self, root: Optional[TreeNode], targetSum: int) -> bool:
if not root:
return False
if not root.left and not root.right:
return root.val == targetSum
return self.hasPathSum(root.left, targetSum - root.val) or self.hasPathSum(root.right, targetSum - root.val)
C++•path-sum/synced-solution.cpp
class Solution {
public:
bool hasPathSum(TreeNode* root, int targetSum) {
if (!root) return false;
if (!root->left && !root->right) return root->val == targetSum;
return hasPathSum(root->left, targetSum - root->val) || hasPathSum(root->right, targetSum - root->val);
}
};
TypeScript•path-sum/synced-solution.ts
function hasPathSum(root: TreeNode | null, targetSum: number): boolean {
if (!root) return false;
if (!root.left && !root.right) return root.val === targetSum;
return hasPathSum(root.left, targetSum - root.val) || hasPathSum(root.right, targetSum - root.val);
}