113.Path Sum II

Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.

For example:
Given the below binary tree and sum = 22,

              5
             / 
            4   8
           /   / 
          11  13  4
         /      / 
        7    2  5   1

return

[
   [5,4,11,2],
   [5,8,4,5]
]

思路:DFS. 如果root为空,直接返回空数组,否则调用help函数。help函数将传入的root节点值压入cur数组,更新当前数组cur的和值now,如果root为叶子节点,且cur数组和为target,则将cur数组压入ret。如果左子结点不为空,递归调用 help(root->left,cur,now,target),右子结点不为空,递归调用 help(root->right,cur,now,target)。请注意,cur数组不能传入引用参数,应该传入形参。每个递归函数在运行过程中对cur数组的操作都是各自为政,互不干涉的。

 
/**
 * 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>> ret;
    void help(TreeNode *root,vector<int> cur,int now,int target){
        now+=root->val;
        cur.push_back(root->val);
        if(!root->left&&!root->right){
            if(now==target)
                ret.push_back(cur);
            return;
        }
        if(root->left)
            help(root->left,cur,now,target);
        if(root->right)
            help(root->right,cur,now,target);
    }
    vector<vector<int>> pathSum(TreeNode* root, int sum) {
        if(!root)
            return ret;
        vector<int> temp;
        help(root,temp,0,sum);
        return ret;
    }
};

 



原文地址:https://www.cnblogs.com/zhoudayang/p/5043195.html