Path Sum

该博客介绍了两个二叉树问题,分别为PathSum和PathSum2。PathSum寻找从根节点开始的所有路径,其路径元素之和等于给定值。PathSum2则要求路径必须以叶子节点结束且满足同样的条件。通过递归的pathSumHelper函数,可以找到所有符合条件的路径。
摘要由CSDN通过智能技术生成

Path Sum

题目:Get all the paths(always starts from the root) in a binary tree,whose sum would be equal to given value.

void pathSumHelper(vector<int> &path,vector<vector<int>> &result,TreeNode *root,int sum){
    if(root == NULL)    return;
    path.push_back(root->val);
    if(root->val == sum)
        result.push_back(path);
    pathSumHelper(path,result,root->left,sum - root->val);
    pathSumHelper(path,result,root->right,sum - root->val);
    path.pop_back();//注意此步不可少.
}

vector<vector<int>> pathSum(TreeNode *root,int sum){

    vector<int> path;
    vector<vector<int>> result;
    pathSumHelper(path,result,root,sum);
    return result;
}

Path Sum2

题目:Get all the paths (always starts from the root and ends at leaf)in a binary tree,whose sum would be equal to given value.

void pathSumHelper(vector<int> &path,vector<vector<int>> &result,TreeNode *root,int sum){
    if(root == NULL)    return;
    path.push_back(root->val);
    if(root->val == sum && root->left == NULL && root->right == NULL)
        result.push_back(path);
    pathSumHelper(path,result,root->left,sum - root->val);
    pathSumHelper(path,result,root->right,sum - root->val);
    path.pop_back();
}

vector<vector<int>> pathSum(TreeNode *root,int sum){
    vector<int> path;
    vector<vecotor<int>> result;
    pathSumHelper(path,result,root,sum);
    return result;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

云镛

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值