您的位置:首页 > 职场人生

Leetcode Path Sum II

2013-12-06 14:20 295 查看
dfs,跟Path Sum I 相差无几。

/**
* 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> > pathSum(TreeNode *root, int sum) {
ans.clear();
dfs(root, sum, 0);
return ans;
}
void dfs(TreeNode *root, int sum, int cnt){
if(!root) return ;
if(!root->left && !root->right){
if(cnt + root->val == sum){
v.push_back(root->val);
ans.push_back(v);
v.pop_back();
}
return ;
}
v.push_back(root->val);
dfs(root->left, sum, cnt+root->val);
dfs(root->right, sum, cnt+root->val);
v.pop_back();

}
vector<int> v;
vector<vector<int> > ans;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode 面试 OJ