leetcode 日经贴,Cpp code -Path Sum II

来源:互联网 发布:淘宝宝贝下架怎么上架 编辑:程序博客网 时间:2024/06/06 13:15

Path Sum II

/** * Definition for binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    void dfs(TreeNode *r, vector<int> ¤t, vector<vector<int> >&ans, int cs) {        if(!r) return ;        if (!r->left && !r->right) {            if (cs == r->val) {                current.push_back(r->val);                ans.push_back(current);                current.pop_back();            }            return ;        }        cs -= r->val;        current.push_back(r->val);        dfs(r->left, current, ans, cs);        dfs(r->right, current, ans, cs);        current.pop_back();    }    vector<vector<int> > pathSum(TreeNode *root, int sum) {        vector<vector<int> > ans;        vector<int> cs;        dfs(root, cs, ans, sum);        return ans;    }};


0 0
原创粉丝点击