考虑还是使用深搜,遍历每一棵子树并记录其路径。由于每个节点也可能出现负数,所以不太好剪枝,只能是遍历到叶子节点。
/**
* Definition for binary tree
* 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<int> rper;
vector<vector<int>> res;
if( root == NULL )
{
return res;
}
res = fun( rper,res,root,sum,0 );
return res;
}
vector<vector<int>> fun(vector<int> rper,vector<vector<int>> res,TreeNode *root, int sum,int count)
{
rper.push_back(root->val);
if( root->left == NULL && root->right == NULL && root->val+count == sum )
{
res.push_back(rper);
return res;
}
count += root->val;
if( root->left != NULL )
{
res = fun(rper,res,root->left,sum,count);
}
if( root->right != NULL )
{
res = fun(rper,res,root->right,sum,count);
}
return res;
}
};