[Leetcode] Path Sum II

来源:互联网 发布:head first java web 编辑:程序博客网 时间:2024/05/01 22:23
/** * 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> > pathSum(TreeNode *root, int sum) {        // Start typing your C/C++ solution below        // DO NOT write int main() function        vector<vector<int> > res;        vector<int> buf;        run(root, 0, sum, buf, res);                return res;    }        void run(TreeNode* n, int curSum, int targetSum, vector<int> buf, vector<vector<int> >& res)    {        if (!n) return;                buf.push_back(n->val);        if (!n->left && !n->right && targetSum - n->val == curSum)        {            res.push_back(buf);        }        else        {                        run(n->left, n->val + curSum, targetSum, buf, res);            run(n->right, n->val + curSum, targetSum, buf, res);        }            }};

原创粉丝点击