您的位置:首页 > 其它

LeetCode: Path Sum

2014-08-26 22:37 344 查看
[b]LeetCode: Path Sum[/b]

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      1

return true, as there exist a root-to-leaf path
5->4->11->2
which sum is 22.

地址:https://oj.leetcode.com/problems/path-sum/

算法:用递归应该很简单吧。直接看代码吧:

/**
* Definition for binary tree
* struct TreeNode {
*     int val;
*     TreeNode *left;
*     TreeNode *right;
*     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
if(!root)   return false;
return subSolution(root,sum);
}
bool subSolution(TreeNode *root, int sum){
if(!root->left && !root->right){
if(sum == root->val)    return true;
else    return false;
}else{
if(root->left){
bool left = subSolution(root->left,sum - root->val);
if(left)    return true;
}
if(root->right){
bool right = subSolution(root->right,sum - root->val);
if(right)   return true;
}
}
return false;
}
};


第二题:

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]
]

地址:https://oj.leetcode.com/problems/path-sum-ii/
算法:跟上一题一样,只不过必须返回所有的结果。应该也很简单,直接看代码:


/**
* 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) {
if(!root)   return vector<vector<int> >();
return subPathSum(root,sum);
}
vector<vector<int> > subPathSum(TreeNode *root, int sum){
if(!root->left && !root->right){
if(root->val == sum){
return vector<vector<int> >(1,vector<int>(1,sum));
}else{
return vector<vector<int> >();
}
}
vector<vector<int> > result;
if(root->left){
vector<vector<int> > left = subPathSum(root->left, sum - root->val);
vector<vector<int> >::iterator it = left.begin();
for(; it != left.end(); ++it){
vector<int> temp;
temp.push_back(root->val);
temp.insert(temp.end(),it->begin(),it->end());
result.push_back(temp);
}
}
if(root->right){
vector<vector<int> > right = subPathSum(root->right,sum - root->val);
vector<vector<int> >::iterator it = right.begin();
for(; it != right.end(); ++it){
vector<int> temp;
temp.push_back(root->val);
temp.insert(temp.end(),it->begin(),it->end());
result.push_back(temp);
}
}
return result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: