(M)DFS:113. Path Sum II

来源:互联网 发布:php会员系统源码 编辑:程序博客网 时间:2024/06/06 10:56

这个题是给出一个二叉树,再给一个目标值target,求出所有从根到叶,并且这个路径的和等于这个目标值的所有路径。

/** * Definition for a binary tree node. * 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) {        vector<vector<int>> res;        vector<int> path;        dfs(root, sum, path, res);        return res;    }    void dfs(TreeNode* root, int sum, vector<int> path, vector<vector<int>>& res)    {        if(root == NULL)    return;        if(root->left == NULL && root->right == NULL)        {            if(sum - root->val == 0)            {                path.push_back(root->val);                res.push_back(path);            }            else return;        }        path.push_back(root->val);        dfs(root->left, sum - root->val, path, res);        dfs(root->right, sum - root->val, path, res);    }};