描述
求根节点到叶子节点的路径和等于目标和的所有路径
解决
左右递归
/**
* 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>> res;
vector<int> temp;
vector<vector<int>> pathSum(TreeNode* root, int sum) {
if (!root)
return {};
help(root, 0, sum);
return res;
}
void help(TreeNode* root, int zz, int &sum)
{
//cout << "zz = : " << zz << endl;
if (root -> left == NULL && root -> right == NULL)
{
if (zz + root -> val == sum)
{
temp.push_back(root -> val);
res.push_back(temp);
temp.pop_back();
return ;
}
return ;
}
if (root -> left)
{
temp.push_back(root -> val);
// cout << root -> val << endl;
help(root -> left, zz + root -> val, sum);
temp.pop_back();
}
if (root -> right)
{
temp.push_back(root -> val);
// cout << root -> val << endl;
help(root -> right, zz + root -> val, sum);
temp.pop_back();
}
return ;
}
};