完全理解这道题的话,对递归应该来说理解比较深了,这道题目是递归中嵌套一个递归,dfs主要是求解和等于sum的数量,然后pathSum是根据新的结点,求解符合条件的个数。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if(root)
        {
            dfs(root,sum);
            pathSum(root->left,sum);
            pathSum(root->right,sum);
        }
        return ans;
    }
private:
    int ans = 0;
    void dfs(TreeNode* root,int sum) {
        if(!root) return;
        if(root->val == sum)
            ans += 1;
        dfs(root->left,sum - root->val);
        dfs(root->right,sum - root->val);
    }
};

运行效率:

Runtime: 32 ms, faster than 28.32% of C++ online submissions for Path Sum III.
Memory Usage: 15.7 MB, less than 83.58% of C++ online submissions for Path Sum III.

上面题目中的成员变量ans可以省略,写法如下:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if(!root) return 0;
        return pathSum(root,0,sum) + pathSum(root->left,sum) + pathSum(root->right,sum);
    }
private:
    int pathSum(TreeNode* root,int pre,int sum) {
        if(!root) return 0;
        int current = pre + root->val;
        return (sum == current) + pathSum(root->left,current,sum) + pathSum(root->right,current,sum);
    }
};

运行效率:

Runtime: 32 ms, faster than 28.32% of C++ online submissions for Path Sum III.
Memory Usage: 15.5 MB, less than 92.29% of C++ online submissions for Path Sum III.