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] ]Tree Depth-first Search
思路:与Path Sum 类似,只是function函数多一个参数记录当前的路径
/**
* 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>> res;
void function(TreeNode *root,int num,vector<int> v)
{
if(root==NULL)
{
if(num==0)
res.push_back(v);
}
else{
int temp=num-root->val;
vector<int> tmp(v);
tmp.push_back(root->val);
if(root->left==NULL&&root->right==NULL)
function(root->left,temp,tmp);
else if(root->left==NULL&&root->right!=NULL)
function(root->right,temp,tmp);
else if(root->left!=NULL&&root->right==NULL)
function(root->left,temp,tmp);
else{
function(root->left,temp,tmp);
function(root->right,temp,tmp);
}
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
if(root==NULL)
return res;
vector<int> v;
function(root,sum,v);
return res;
}
};