[Leetcode] #112#113 Path Sum I & II
2017-02-10 15:27
483 查看
Path Sum I:
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.For example:Given the below binary tree and
sum = 22,
5 / \ 4 8 / / \ 11 13 4 / \ \ 7 2 1return true, as there exist a root-to-leaf path
5->4->11->2which sum is 22.
Solution:
bool hasPathSum(TreeNode* root, int sum) { if (root == NULL) return false; if (root->val == sum && root->left == NULL && root->right == NULL) return true; return hasPathSum(root->left, sum - root->val) || hasPathSum(root->right, sum - root->val); }
Path Sum II:
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 1return
[
[5,4,11,2],
[5,8,4,5]
]
Solution:
采用DFS,给出两种稍微不同的递归写法。void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res){
path.push_back(root->val);
sum -= root->val;
if (sum == 0 && !root->left && !root->right)
res.push_back(path);
if (root->left)
pathSum(root->left, sum, path, res);
if (root->right)
pathSum(root->right, sum, path, res);
path.pop_back();
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> ans;
if (!root) return ans;
vector<int> path;
pathSum(root, sum, path, ans);
return ans;
}
void pathSum(TreeNode* root, int sum, vector<int> &path, vector<vector<int>> &res) { if (!root) return; path.push_back(root->val); sum -= root->val; if (sum == 0 && !root->left && !root->right) res.push_back(path); pathSum(root->left, sum, path, res); pathSum(root->right, sum, path, res); path.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> ans; vector<int> path; pathSum(root, sum, path, ans); return ans; }GitHub-LeetCode: https://github.com/wenwu313/LeetCode
相关文章推荐
- 【LeetCode】Unique Paths I && II && Minimum Path Sum
- [Leetcode]Path Sum&Path Sum II
- 【leetcode】Path Sum I && II
- LeetCode-Path Sum II<ERROR>
- LeetCode之“动态规划”:Minimum Path Sum && Unique Paths && Unique Paths II
- 【LeetCode】path-sum i&ii
- LeetCode | Unique Paths & II & Minimum Path Sum
- Leetcode | Path Sum I && II
- LeetCode之“树”:Path Sum && Path Sum II
- [Leetcode][JAVA] Path Sum I && II
- Path Sum & Path Sum II | LeetCode DFS
- [leetcode]_Path Sum I && II
- [Leetcode]Path Sum && Path Sum II
- [LeetCode] Unique Paths && Unique Paths II && Minimum Path Sum (动态规划之 Matrix DP )
- LeetCode:Path Sum I &&II
- [LeetCode 112 113] - 路径和I & II (Path Sum I & II)
- [LeetCode]112. Path Sum&113. Path Sum II
- Leetcode: Unique Path I & II, Minimum Path Sum, Triangle
- [LeetCode] Path Sum && Path Sum II
- 【leetcode】Path Sum I & II(middle)