题目:
Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
代码如下:
void haspath(TreeNode *root,int &m_sum, int &sum,vector<int> &p,vector<vector<int> > &result)
{
m_sum+=root->val;
p.push_back(root->val);
if(root->left!=NULL)
{
haspath(root->left,m_sum,sum,p,result);
}
if(root->right!=NULL)
{
haspath(root->right,m_sum,sum,p,result);
}
if(root->left==NULL&&root->right==NULL)
{
if(m_sum==sum)
{
result.push_back(p);
}
}
m_sum-=root->val;
p.pop_back();
return;
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
if(root==NULL)return result;
vector<int> p;
int m_sum=0;
key=false;
haspath(root,m_sum,sum,p,result);
return result;
}