您的位置:首页 > 其它

Leetcode146: Path Sum II

2015-11-09 19:04 295 查看
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]
]


/**
* Definition for a binary tree node.
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(vector<vector<int>>& res, vector<int>& tmp, int sum, int cursum, TreeNode* root)
{
if(!root)   return ;
cursum += root->val;
tmp.push_back(root->val);
if(cursum == sum && !root->left && !root->right)
{
res.push_back(tmp);
}
dfs(res, tmp, sum, cursum, root->left);
dfs(res, tmp, sum, cursum, root->right);
tmp.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> tmp;
vector<vector<int>> res;
dfs(res, tmp, sum, 0, root);
return res;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: