问题
思路
和之前的那一道只是在接口上有区别而已。
代码
/**
* 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) {
std::vector<std::vector<int>> ret;
std::vector<int> nodes;
if(!root) return ret;
dfs(root, sum, 0, nodes, ret);
return ret;
}
private:
void dfs(TreeNode* root, int sum, int res, std::vector<int> nodes, std::vector<std::vector<int>>& ret){
if(root){
res += root->val;
nodes.push_back(root->val);
if(!root->left && !root->right){
if(res==sum) ret.push_back(nodes);
}
dfs( root->left, sum, res, nodes, ret );
dfs( root->right, sum, res, nodes, ret );
}
}
};
思路1
保持了和path sum一样的做法,在传递参数的时候,传递了path的引用,那么当前节点访问完毕之后,要把该节点退出path。
代码1
/**
* 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) {
std::vector<std::vector<int>> ret;
if(!root) return ret;
std::vector<int> path;
dfs(root, sum, path, ret);
return ret;
}
private:
void dfs(TreeNode* root, int sum, std::vector<int>& path, std::vector<std::vector<int>>& ret){
if(!root) return;
path.push_back(root->val);
if(!root->left&&!root->right&&root->val==sum) ret.push_back(path);
dfs(root->left, sum-root->val, path, ret);
dfs(root->right, sum-root->val, path, ret);
path.pop_back();
}
};
思路2
二叉树的题目,对边界情况的处理比较灵活,其实就那么几种情况,如果不确定,分别试下即可。这个题dfs遍历即可。由于path是引用,所以头尾插入和删除是对称的,这样不会影响其他层次的遍历。
/**
* 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>> ret;
if(!root) return ret;
vector<int> path;
dfs( root, 0, sum, path, ret );
return ret;
}
private:
void dfs(TreeNode* root, int cur, int target, vector<int>& path, vector<vector<int>>& ret){
if( root ){
path.push_back(root->val);
cur += root->val; // cur本身就是值传递,当前层变了之后也不会影响上一层
if( !root->left && !root->right ){
if( cur == target )
ret.push_back(path);
}else{
dfs(root->left, cur, target, path, ret);
dfs(root->right, cur, target, path, ret);
}
path.pop_back();
}
}
};