dfs。前序遍历,当达到叶子节点并且和满足要求时,保存此路径,递归的过程中还要对路径进行回溯。

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 * };
 */

class Solution {
public:
    /**
     * 
     * @param root TreeNode类 
     * @param sum int整型 
     * @return int整型vector<vector<>>
     */
    void pre_order(TreeNode* root,vector<vector<int>>& result,vector<int>& path,int sum){
        path.push_back(root->val);
        if(root->left==nullptr && root->right==nullptr){
            int a_sum=0;
            for(auto x: path) a_sum+=x;
            if(a_sum==sum) result.push_back(path);
            return;
        }
        if(root->left){
            pre_order(root->left, result, path, sum);
            path.pop_back();
        }
        if(root->right){
            pre_order(root->right, result, path, sum);
            path.pop_back();
        }
    }
    
    vector<vector<int> > pathSum(TreeNode* root, int sum) {
        if(root==nullptr) return {};
        vector<vector<int>> result;
        vector<int> path;
        pre_order(root,result,path,sum);
        return result;
    }
};