113. Path Sum II

来源:互联网 发布:贴吧防秒删软件 编辑:程序博客网 时间:2024/05/02 05:00

使用递归的方法,传递path变量,sum减去经过path经过节点的值,最后为0,且为根节点即可。

class Solution {public:    vector<vector<int>> pathSum(TreeNode* root, int sum) {        vector<int> path;        vector<vector<int>> allPath;        findPath(root, sum, path, allPath);        return allPath;    }    void findPath(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &allPath)    {        if(!root) return;        sum -= root->val;        path.push_back(root->val);        if(!root->left && !root->right)        {    if(sum == 0)                allPath.push_back(path);        }        else        {            if(root->left) findPath(root->left, sum, path, allPath);            if(root->right) findPath(root->right, sum, path, allPath);        }        path.pop_back();    }};
0 0
原创粉丝点击