题目描述:
给定一个二叉树和一个值\ sum sum,请找出所有的根节点到叶子节点的节点值之和等于\ sum sum 的路径,
解题分析:
采用递归的思想,依次累加,记录从根节点到叶子节点总和为sum的路径即可。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector<vector<int>> paths;
vector<int> path;
recursionPathSum(root, 0, sum, path, paths);
return paths;
}
void recursionPathSum(TreeNode* root, int currSum, int sum, vector<int> path, vector<vector<int>>& paths){
if(root==NULL)
return;
path.push_back(root->val);
currSum+=root->val;
if(root->left == NULL && root->right==NULL && currSum==sum){
paths.push_back(path);
return;
}
recursionPathSum(root->left, currSum, sum, path, paths);
recursionPathSum(root->right, currSum, sum, path, paths);
return;
}
};