LeetCode_Path Sum II
来源:互联网 发布:蜂窝移动网络 编辑:程序博客网 时间:2024/06/05 15:54
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]]
这道题和他的兄弟题目一样,都是DFS,但是我很困惑的是我的代码MLE,于是看了http://www.cnblogs.com/remlostime/archive/2012/11/13/2767760.html上的代码,发现我们的代码惊人的相似,但是他的AC了,郁闷,谁要是知道为什么?求讲解。
我的代码:
class Solution {public: vector<vector<int> > pathSum(TreeNode *root, int sum) { vector <vector <int>> result; vector <int> path; int currentSum=0; pathSum(root,sum,result,path,currentSum); return result; } //Memory Limit Exceed void pathSum(TreeNode *root,const int &sum,vector<vector<int>> &res, vector <int> &path,int ¤tSum){ if(root==NULL){ return; } path.push_back(root->val); //还没达到叶节点 currentSum+=root->val; if (root->left!=NULL||root->right!=NULL){ pathSum(root->left,sum,res,path,currentSum); pathSum(root->left,sum,res,path,currentSum); } else{ if(currentSum==sum){ res.push_back(path); } } currentSum-=root->val; path.pop_back(); }};AC代码:
class Solution {private: vector<vector<int> > ret;public: void dfs(TreeNode *node, int sum, int curSum, vector<int> a) { if (node == NULL) return; if (node->left == NULL && node->right == NULL) { if (curSum + node->val == sum) { a.push_back(node->val); ret.push_back(a); } return; } a.push_back(node->val); dfs(node->left, sum, curSum + node->val, a); dfs(node->right, sum, curSum + node->val, a); } vector<vector<int> > pathSum(TreeNode *root, int sum) { // Start typing your C/C++ solution below // DO NOT write int main() function ret.clear(); vector<int> a; dfs(root, sum, 0, a); return ret; }};
My Submissions for Path Sum II
0 0
- LeetCode_Path Sum II
- *Leetcode_path-sum-ii
- LeetCode_Path Sum II
- Leetcode_Path Sum II
- LeetCode_Path Sum II
- LeetCode_Path Sum
- LeetCode_Path Sum
- Leetcode_Path Sum
- LeetCode_Path Sum
- LeetCode_path-sum
- Leetcode_path-sum (updated c++ and python version)
- 【Leetcode】Path Sum II (Sum)
- Combination Sum && Combination Sum II
- Combination Sum Combination Sum II
- Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Combination Sum II
- LeetCode: Path Sum II
- 打包winform程序时,处理app.config
- Draw3dRect
- 盒址浅倥樟菊疟剐呈加锻剐墓傻倥
- 山韵蚁扒樟夏藕樟匣浅恐官谄浅灰
- php扩展
- LeetCode_Path Sum II
- HDU 2896 病毒侵袭 (AC自动机)
- DB2数据库常用命令集:部分数据库维护命令
- Spring--在Bean定义中使用EL
- Hdu 3507 Print Article (线性DP)
- ORA-00119: invalid specification for system parameter LOCAL_LISTENER
- Tachyon架构分析和现存问题讨论
- 迷宫问题的C语言求解
- 详细讲解DB2数据库性能监控的具体步骤