Path Sum
此题同 leetcode Sum Root to Leaf Numbers 解法,递归遍历时改变每个节点的值,该值为从起点到当前节点的路径和。
代码
class Solution {
public:
bool hasPathSum(TreeNode *root, int sum) {
flag = false;
hasPathSumHelper(root, sum);
return flag;
}
void hasPathSumHelper(TreeNode *root, int sum)
{
if(root==NULL)
return ;
if(!root->left&&!root->right&&root->val==sum)
{
flag = true;
return ;
}
if(root->left!=NULL)
{
root->left->val += root->val;
hasPathSumHelper(root->left,sum);
}
if(root->right!=NULL)
{
root->right->val += root->val;
hasPathSumHelper(root->right,sum);
}
}
private:
bool flag;
};
Path Sum ||
与Path Sum 大致相同,但要求输出所有路径和满足条件的路径,因此开辟空间保存路径信息即可。
代码
class Solution {
public:
vector<vector<int> > pathSum(TreeNode *root, int sum) {
vector<vector<int> > result;
vector<int> onePath;
if(root==NULL)
return result;
onePath.push_back(root->val);
pathSumHelper(root, sum, onePath, result);
return result;
}
void pathSumHelper(TreeNode *root, int sum, vector<int> onePath, vector<vector<int> > &result)
{
if(root==NULL)
return ;
if(!root->left&&!root->right&&root->val==sum)
{
result.push_back(onePath);
}
if(root->left)
{
onePath.push_back(root->left->val);
root->left->val += root->val;
pathSumHelper(root->left, sum, onePath, result);
onePath.pop_back();
}
if(root->right)
{
onePath.push_back(root->right->val);
root->right->val += root->val;
pathSumHelper(root->right, sum, onePath, result);
onePath.pop_back();
}
}
};