比较简单的bfs遍历,最开始写完之后卡在第13个用例没通过,看了半天代码没发现原因。最后去看了别人的代码,发现每次递归结束之后忘了pop_back(),这就很尴尬。因为在递归中是用同一个数组来记录路径的,所以在一次递归结束后必须要把该路径上的结点去除,才能用于记录另一路径。
/**
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
class Solution {
public:
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型vector<vector<>>
*/
vector<vector<int> > pathSum(TreeNode* root, int sum) {
// write code here
vector<vector<int>> result;
if(!root){
return result;
}
vector<int> ns;
find(result, root, sum, 0, ns);
return result;
}
void find(vector<vector<int>> &result,TreeNode* p,int sum, int now,vector<int> &ns){
now += p->val;
ns.push_back(p->val);
if(p->left){
find(result,p->left,sum,now,ns);
}
if(p->right){
find(result, p->right, sum, now,ns);
}
if(!p->left && !p->right && now == sum){
result.push_back(ns);
}
//Key sentence.
ns.pop_back();
}
}; 
京公网安备 11010502036488号