题目描述
给定一个二叉树和一个值\ sum sum,请找出所有的根节点到叶子节点的节点值之和等于\ sum sum 的路径,
例如:
给出如下的二叉树, sum=22,
返回 [ [5,4,11,2], [5,8,9] ]
思路
- 利用递归的先序遍历,每次储存遍历过的节点,并用sum去减,最后判断是否为0
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
// 先序遍历,
void dfs(TreeNode* root, int sum, vector<vector<int>> &res, vector<int> path){
if(root == NULL)
return ;
path.push_back(root->val);
if(!root->left && !root->right && sum == root->val)
res.push_back(path);
dfs(root->left, sum-root->val, res, path);
dfs(root->right, sum-root->val, res, path);
}
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector<vector<int>> res;
vector<int> path;
dfs(root, sum, res, path);
return res;
}
};
错因
- res数组没有用值传递