二叉树中和为某一值的路径
    题目链接:https://leetcode-cn.com/problems/er-cha-shu-zhong-he-wei-mou-yi-zhi-de-lu-jing-lcof/
    图片.png

    思路:递归,每次从target中减去当前节点的值,终止条件为判断到达叶子节点时target是否为0. 返回上层时把当前节点的值要pop出去。

    参考代码:

    1. class Solution {
    2. public:
    3. vector<vector<int>> pathSum(TreeNode* root, int target) {
    4. vector<vector<int>> res;
    5. if (!root) {
    6. return res;
    7. }
    8. vector<int> path;
    9. recursionSum(root, target, res, path);
    10. return res;
    11. }
    12. void recursionSum(TreeNode* root, int target, vector<vector<int>>& res, vector<int>& path) {
    13. if (!root) {
    14. return;
    15. }
    16. path.push_back(root->val);
    17. target -= root->val;
    18. if (!root->left && !root->right) {
    19. if (target == 0) {
    20. res.push_back(path);
    21. }
    22. }
    23. recursionSum(root->left, target, res, path);
    24. recursionSum(root->right, target, res, path);
    25. path.pop_back();
    26. return;
    27. }
    28. };