C++ recursive solution


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

Log in to reply
 

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