原题:
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
,
这个题跟第一个基本一样,看看第一个。就是需要返回一个路径,由于有多个路径,因此用vector<vector<int>>保存路径。就是在vector的插入时,需要注意insert和vector的begin()。
代码(84 ms):
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
// IMPORTANT: Please reset any member data you declared, as
// the same Solution instance will be reused for each test case.
vector<vector<int> >result;
if(root==NULL){
return result;
}
if(root->left==NULL && root->right==NULL){
//左右都为NULL,说明是叶子节点
if(root->val == sum) {
//叶子节点返回一个vector<vector<int>>的类型
vector<int>path;
path.push_back(sum);
result.push_back(path);
}
return result;;
}
if(root->left != NULL){
//左子树的path
vector<vector<int> >leftV = pathSum(root->left , sum - root->val);
//对左子数的每条path的第一个位置加入当前的val
for(int i =0 ;i<leftV.size() ; i++){
// vector begin,意味着将root->val插入第一个位置
leftV[i].insert(leftV[i].begin() , root->val);
result.push_back(leftV[i]);
}
}
if(root->right != NULL){
vector<vector<int> >rightV = pathSum(root->right , sum - root->val);
for(int i =0 ;i<rightV.size() ; i++){
rightV[i].insert(rightV[i].begin() , root->val);
result.push_back( rightV[i] );
}
}
return result;
}
};