Recursive C++ solution passed all test cases


  • 0
    C
    class Solution {
    public:
        int fromRootSum(TreeNode* root, int sum) {
            if (!root) {
                return 0;
            }
            if (sum == root->val) {
                return 1 + fromRootSum(root->left, 0) + fromRootSum(root->right, 0); 
            }
            return fromRootSum(root->left, sum - root->val) + fromRootSum(root->right, sum - root->val);
        }   
    
        int pathSum(TreeNode* root, int sum) {
            if (!root) {
                return 0;
            }
            int result = fromRootSum(root, sum);
            result += pathSum(root->left, sum) + pathSum(root->right, sum);
            return result;
        }   
    };
    

Log in to reply
 

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