auto-generated entry for Path Sum. the solution files are available below.
solution files
- C++
path-sum/synced-solution.cpp - Python
path-sum/synced-solution.py - TypeScript
path-sum/synced-solution.ts
Collected C++, Python, TypeScript solutions for path sum. Add a dedicated write-up later if you want deeper notes.
auto-generated entry for Path Sum. the solution files are available below.
path-sum/synced-solution.cpppath-sum/synced-solution.pypath-sum/synced-solution.tsclass 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)
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);
}
};
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);
}