【leetcode c++】113 Path Sum II
来源:互联网 发布:wex5仿微店源码下载 编辑:程序博客网 时间:2024/06/11 12:06
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,
Return
Path Sum二号题刚好和一号题连在一起,就顺便做了。这次要求是的把路径记下来。所以呢,路径可能不止一条,所以必须要把整棵树遍历。所谓的路径是一个root-to-leaf path。所以从根节点开始,先保证有一个数组来存放路径。但是我们把这个数组当作栈来用,也就是使用push_back、pop_back。每进入一个节点就push,离开以这个节点为根的树就pop,到达叶子节点就判断是否是所求路径。
这题其实不是很难想,应该考验的是你如何减少无用的时间空间消耗。因为,题目要求的结果要放在vector二维数组中。策略不对可能就要多耗时。
开始
比如这棵树,求sum=6,结果应该是2个[1,2,3]
从根节点遍历到第一个(从左到右)叶子节点时,这个路径是符合的,那么我们需要把这个路径保存下来,也就是复制一个路径出来,把这个副本作为结果保存起来,原来的路径则在遍历回节点2的时候pop操作。
其实也就是,深度优先。这个在数据结构清华大学出版社的书里面的栈的那部分,有一题迷宫求出口的题,也是深度优先来解。这个题其实也可以理解成一个迷宫求路径的问题。只不过,这个‘迷宫‘路径有很多条,判定出口规则也不一样。
**************************
**************************
**************************
**************************
**************************
我们发现,保存路径的那个vector数组时刻在变化,只有找到合法路径的时候,才会丢一个副本进入结果二维数组中,所以这个路径数组我们应当让它唯一,所以我传了引用。找到了合法路径就直接push_back即可,因为push_back进去的本来就只是个副本,我们可以传引用。
代码:
/** * 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: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int>> res; if(NULL == root) return res; vector<int> temp; int preSum = 0; Lv(root, sum, preSum, temp, res); } void Lv(TreeNode* root,int sum, int& preSum, vector<int>& temp, vector<vector<int>>& res) { if(NULL == root) return; //进入节点就push preSum += root->val; temp.push_back(root->val); if(!root->left && !root->right) { if(sum == preSum) { res.push_back(temp);//路径找到,copy到二维数组中 } preSum -= root->val; temp.pop_back(); return; } Lv(root->left, sum, preSum, temp, res); Lv(root->right, sum, preSum, temp, res); //离开节点就pop preSum -= root->val; temp.pop_back(); }};
2015-07-28
- 【leetcode c++】113 Path Sum II
- LeetCode 113: Path Sum II
- LeetCode(113)Path Sum II
- LeetCode: Path Sum II [113]
- [leetcode 113] Path Sum II
- [LeetCode 113]Path Sum II
- leetcode || 113、Path Sum II
- Leetcode[113]-Path Sum II
- Path Sum II - LeetCode 113
- 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
- 多租户--EclipseLink实现
- Ubuntu+win7安装总结——查询不到win7分区问题
- poj 2315 最小费用最大流入门题
- HDU - 2145 zz's Mysterious Present (最短路)
- universal image loader在listview/gridview中滚动时重复加载图片的问题及解决方法
- 【leetcode c++】113 Path Sum II
- Hibernate
- SpringMVC+Spring+Hibernate配置
- 数据库层预克隆报无法创建日志文件
- git建立远程仓库
- TextView的日常使用技巧
- 1064. Complete Binary Search Tree (30)
- 关于C++虚函数和纯虚函数
- struts2的default.properties详解