Leetcode 113. Path Sum II
来源:互联网 发布:大公司程序员职业规划 编辑:程序博客网 时间:2024/05/17 14:16
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 1
return
[ [5,4,11,2], [5,8,4,5]]第一次写有关二叉链表的深搜,心里有些小紧张.......
代码如下:
是通过两个容器的过渡作用,将能求出目标和的路径保存在单个容器中再存在有嵌套的容器中 再返回嵌套容器
class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<vector<int>>ress; //用来存放路径
vector<int>res; //用来暂时存放路径
dfs(root,sum,res,ress); //搜索这棵树,将能达到sum的路径保存在嵌套容器中
return ress;
}
void dfs(TreeNode* root, int sum,vector<int>&res,vector<vector<int>>&ress)
{
if(!root) //如果是空树就直接return即可,什么也不用做
return;
else if(sum==root->val&&!root->left&&!root->right) //递归出口,如果是叶节点并且达到目标值的话,就把该节点放入一重容器,再将该一重容器放到嵌套容器中
{
res.push_back(root->val);
ress.push_back(res);
res.pop_back(); //特别注意,一定要将该节点从一重容器中删除掉,因为如果不删除,回溯时实际上是要从容器中删除它的上一个节点的值
return; //但如果没删掉该节点,多余的该节点就会占用在容器中,使得删除的不是上一个节点而是该节点,这样会让下一次
} //再找到一条合适的路径时,容器中多一个值,进而导致答案错误
res.push_back(root->val); //不管怎样都先将该点的值放入容器
dfs(root->left,sum-root->val,res,ress); //递归搜索左子树
dfs(root->right,sum-root->val,res,ress); //递归搜索右子树
res.pop_back(); //如果该点的所有情况考虑完了,就将容器中的该点的值删除
}
};
- LeetCode 113. Path Sum II
- [LeetCode]113.Path Sum II
- [Leetcode] 113. Path Sum II
- [leetcode] 113.Path Sum II
- [LeetCode]113. Path Sum II
- LeetCode: 113. Path Sum II
- leetcode 113. Path Sum II
- 113. Path Sum II LeetCode
- leetcode 113. Path Sum II
- LeetCode *** 113. Path Sum II
- Leetcode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode - 113. Path Sum II
- Leetcode 113. Path Sum II
- [LeetCode] 113. Path Sum II
- [leetcode] 113. Path Sum II
- [LeetCode] 113. Path Sum II
- scikit-learn 中文文档-高斯过程-监督学习|ApacheCN
- UVA 11374 SPFA+路径打印
- 人工智能学习清单
- POJ 1129.Channel Allocation
- 两种快速排序的实现(C语言)
- Leetcode 113. Path Sum II
- Ubuntu14.04 增加Swap分区
- 一个轻量级的分布式RPC框架
- request、response 中文乱码问题与解决方式
- mysql 练习1 完成一个由 学生表 选课表 课程表 的一个多表查询
- 1003. Emergency (25)(java版)
- AngularJS http 服务
- RedHat 安装 f2fs-tools
- hibernate知识