15 Jun 2024C++ / Python / TypeScriptEasy

Path Sum

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.

solution files

  • C++ path-sum/synced-solution.cpp
  • Python path-sum/synced-solution.py
  • TypeScript path-sum/synced-solution.ts

Solution files

Pythonpath-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);
    }
};
TypeScriptpath-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);
}