[LeetCode] Path Sum II
2014-01-04 11:21
357 查看
问题:
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
return
分析:
有点像permutation那道题。
代码:
class Solution {
public:
void pathSum(vector<vector<int> > &result, vector<int> temp, TreeNode *root, int sum) {
if (!root) return;
if (root->val == sum && !root->left && !root->right) {
temp.push_back(root->val);
result.push_back(temp);
return;
}
else {
temp.push_back(root->val);
pathSum(result, temp, root->left, sum - root->val);
pathSum(result, temp, root->right, sum - root->val);
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> temp;
pathSum(result, temp, root, sum);
return result;
}
};
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] ]
分析:
有点像permutation那道题。
代码:
class Solution {
public:
void pathSum(vector<vector<int> > &result, vector<int> temp, TreeNode *root, int sum) {
if (!root) return;
if (root->val == sum && !root->left && !root->right) {
temp.push_back(root->val);
result.push_back(temp);
return;
}
else {
temp.push_back(root->val);
pathSum(result, temp, root->left, sum - root->val);
pathSum(result, temp, root->right, sum - root->val);
}
}
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> temp;
pathSum(result, temp, root, sum);
return result;
}
};
相关文章推荐
- [leetCode刷题笔记]113. Path Sum II
- LeetCode Path Sum II
- [LeetCode] Path Sum II
- [LeetCode] Path Sum II
- LeetCode: Path Sum II
- Leetcode Path Sum II
- leetcode 113 Path Sum II
- [LeetCode]Path Sum II
- [leetcode] 113. Path Sum II 解题报告
- LeetCode: Path Sum II
- LeetCode题解——Path Sum II
- leetcode:Path Sum II
- Leetcode 113. Path Sum II
- LeetCode | Path Sum II
- [LeetCode] Path Sum II 二叉树路径之和之二
- LeetCode Path Sum II
- leetcode-113. Path Sum II
- leetcode[113]Path Sum II
- leetcode path sum II
- LeetCode113 Path Sum II