LeetCode_Path Sum II
2015-06-30 14:17
519 查看
一.题目
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类似,解法也是相同的吗,只是不能进行剪枝而已。版权所有,欢迎转载,转载请注明出处,谢谢
相关文章推荐
- 使用C++实现JNI接口需要注意的事项
- 关于指针的一些事情
- c++ primer 第五版 笔记前言
- share_ptr的几个注意点
- 动易2006序列号破解算法公布
- Ruby实现的矩阵连乘算法
- C#插入法排序算法实例分析
- Lua教程(一):在C++中嵌入Lua脚本
- Lua教程(二):C++和Lua相互传递数据示例
- C#数据结构与算法揭秘二
- 算法练习之从String.indexOf的模拟实现开始
- C#算法之关于大牛生小牛的问题
- C++联合体转换成C#结构的实现方法
- C#实现的算24点游戏算法实例分析
- C++编写简单的打靶游戏
- C++ 自定义控件的移植问题
- C++变位词问题分析
- C/C++数据对齐详细解析
- C++基于栈实现铁轨问题
- C++中引用的使用总结