您的位置:首页 > 其它

LeetCode:Path Sum系列

2016-07-19 20:12 309 查看

Path Sum

1、题目:Path Sum

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.

2、代码:

/**
* 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:
bool hasPathSum(TreeNode* root, int sum) {
if(root)
{
sum-=root->val;
if(!(root->left||root->right))
{
if(sum==0)
{
return true;
}
else
{
return false;
}
}
bool bleft=false,bright=false;
if(root->left)
{
bleft=hasPathSum(root->left,sum);
}
if(root->right)
{
bright=hasPathSum(root->right,sum);
}
return bleft||bright;
}
else
{
return false;
}
}
};


Path Sum II

1、题目:

Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.

2、代码:

/**
* 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 path(TreeNode* root,vector<vector<int>> &v)
{
if(root)
{
auto iter=v.rbegin();
iter->push_back(root->val);
vector<int> v0{*iter};
path(root->left,v);
if(root->right)
{
if(root->left)  v.push_back(v0);
path(root->right,v);
}
}
}
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>> v{};
if(root)
{
v.push_back({root->val});
path(root->left,v);
if(root->right)
{
if(root->left)  v.push_back({root->val});
path(root->right,v);
}
}
for(auto iter=v.begin();iter!=v.end();)
{
int i=0;
for(const int &im:*iter)
{
i+=im;
}
if(i!=sum)
{
iter=v.erase(iter,iter+1);//vector函数
}
else
{
++iter;
}
}
return v;
}
};


3、总结:

这个是先将路径都求出来然后,然后删除不符合的部分,这绝对不是一个好办法,以后发现更好的思路,再改。

附:Binary Tree Paths

1、题目:

Given a binary tree, return all root-to-leaf paths.。

2、代码:

/**
* 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 binaryTreePaths(TreeNode* root,vector<string> &v)
{
if(root)
{
auto iter=v.rbegin();
stringstream ss;
ss<<root->val;
*iter+=("->"+ss.str());
string s{*iter};
if(root->left)
{
binaryTreePaths(root->left,v);
}
if(root->right)
{
if(root->left)  v.push_back(s);
binaryTreePaths(root->right,v);
}
}
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> v{};
if(root)
{
//写出开头
stringstream ss;
ss<<root->val;
v.push_back(ss.str());
if(root->left)
{
binaryTreePaths(root->left,v);
}
if(root->right)
{
if(root->left)  v.push_back(ss.str());
binaryTreePaths(root->right,v);
}
}
return v;
}
};


3、总结:

弄清楚叶子节点,当左子为空的时候,不用再添加,直接在后面尾元素处理右子。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  leetcode