Description

https://oj.leetcode.com/problems/path-sum/

Difficulty: 2.0/5.0

Analysis and solution

I am so happy that I came up with such a concise solution…

Note: sum can be negative…

class Solution {
public:
    bool hasPathSum(TreeNode *root, int sum){
        if (!root) return false;
        sum -= root->val;
        return (!root->left && !root->right && !sum) || hasPathSum(root->left, sum) || hasPathSum(root->right, sum);
    }

};

Comments