LeetCode_Path Sum II
2016-01-18 17:51
411 查看
一.题目
Path Sum II
Total Accepted: 46778 Total Submissions: 175830MySubmissions
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] ]
Show Tags
Have you met this question in a real interview?
Yes
No
Discuss
二.解题技巧
这道题和LeetCode_Path Sum类似,仅仅只是这道题须要找到全部和等于给定值的路径,因此不能在中间部分进行剪枝。必须遍历全然部的路径。这里面有一个技巧,在进入每个结点的时候。先将该结点的值push到vector中。在退出时间该结点的值pop出来,这样就能够避免有时会忘记pop结点的值的情况。
这样的做法的时间复杂度为O(n),空间复杂度为O(logn)。
三.实现代码
#include <iostream> #include <vector> using std::vector; /** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ struct TreeNode { int val; TreeNode *left; TreeNode *right; TreeNode(int x) : val(x), left(NULL), right(NULL) {} }; class Solution { private: void pathSum(TreeNode* root, int sum, vector<vector<int> > &Result, vector<int> &TmpResult) { if (!root) { return; } if (!root->left && !root->right && root->val == sum) { TmpResult.push_back(sum); Result.push_back(TmpResult); // pop the leaf node TmpResult.pop_back(); return; } int SumChild = sum - root->val; TmpResult.push_back(root->val); pathSum(root->left, SumChild, Result, TmpResult); pathSum(root->right, SumChild, Result, TmpResult); // pop the current node TmpResult.pop_back(); } public: vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<vector<int> > Result; vector<int> TmpResult; pathSum(root, sum, Result, TmpResult); return Result; } };
四.体会
这道题和LeetCode_Path Sum类似,解法也是同样的吗。仅仅是不能进行剪枝而已。版权全部,欢迎转载。转载请注明出处,谢谢
![](http://static.blog.csdn.net/xheditor/xheditor_emot/default/smile.gif)
![](file:///C:/Users/sheng/AppData/Local/Temp/enhtmlclip/EN2255f125.png)
相关文章推荐
- php mysql实现栏目分类递归
- Android volley 使用OkHttp3.0
- python(1) - 变量小测试
- 单点登录
- C#文件操作
- ASP.NET 可输入下拉原型
- 转:JAVA.NET.SOCKETEXCEPTION: TOO MANY OPEN FILES解决方法
- Android 风格与主题(style and theme)
- android bitmap图片下载三级缓存
- 用spring提供的工具类读取Properties
- PHP PSR-4 Autoloader 自动加载(中文版)
- 外部引入的js函数代码规范(以jquery基础)
- iOS开发代理的实现
- CvMat、IplImage和Mat之间的相互转换
- Java创建线程的两种方法比较
- Yii2.0 场景的简单使用
- Java 刷题
- 动态加载JS脚本到HTML
- RandomAccessFile相关
- [leetcode]Jump Game