Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
1:先序遍历;2:当遇到满足条件的路径时,把路径保存下来;3:注意递归结束条件
vector<vector<int> > pathSum(TreeNode *root, int sum)
{
vector<vector<int > > result;
if(root == NULL)
{
return result;
}
vector<int> temp;
pathSumCore(root, sum, temp, result);
return result;
}
void pathSumCore(TreeNode *root, int &leftValue, vector<int> &temp, vector<vector<int> > &result)
{
temp.push_back(root->val);
leftValue -= root->val;
if(leftValue == 0)
{
if(root->left == NULL && root->right == NULL)
{
result.push_back(temp);
}
}
if(root->left)
{
pathSumCore(root->left, leftValue, temp, result);
}
if(root->right)
{
pathSumCore(root->right, leftValue, temp, result);
}
temp.pop_back();
leftValue += root->val;
}