[LeetCode] Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum. For example: Given the below binary tree and sum = 22,

              5
             / 
            4   8
           /   / 
          11  13  4
         /      / 
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int> > res;
    int sum;
    vector<vector<int> > pathSum(TreeNode *root, int sum) {
        this->sum = sum;
        if(root==NULL)
            return res;
        vector<int> v(1,root->val);
        rootToP(root,root->val,v);
        return res;
    }
private:
    void rootToP(TreeNode *p,int sum,vector<int> &v){
        if(p->left==NULL && p->right==NULL && this->sum == sum)
            res.push_back(v);

        vector<int> v0 = v;
        
        if(p->left != NULL){
            v0.push_back(p->left->val);
            rootToP(p->left,sum+p->left->val,v0);
        }
        v0 = v;
        if(p->right != NULL){
            v0.push_back(p->right->val);
            rootToP(p->right,sum+p->right->val,v0);
        }
    
    }
};
原文地址:https://www.cnblogs.com/Xylophone/p/3890334.html