Simple 12ms C++ solution using recursion


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

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.