Leetcode146: Path Sum II
2015-11-09 19:04
295 查看
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
return
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] ]
/** * 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: void dfs(vector<vector<int>>& res, vector<int>& tmp, int sum, int cursum, TreeNode* root) { if(!root) return ; cursum += root->val; tmp.push_back(root->val); if(cursum == sum && !root->left && !root->right) { res.push_back(tmp); } dfs(res, tmp, sum, cursum, root->left); dfs(res, tmp, sum, cursum, root->right); tmp.pop_back(); } vector<vector<int>> pathSum(TreeNode* root, int sum) { vector<int> tmp; vector<vector<int>> res; dfs(res, tmp, sum, 0, root); return res; } };
相关文章推荐
- The Suspects
- 大数据架构之:Flume
- torch中cmul()函数的用法总结
- OSI七层模型和TCP/IP模型
- 常犯的错误
- Xcode 工程设置及含义
- 1001. A+B Format (20)
- static方法只能调用static方法或者变量
- ZOJ 1001 A+B Problem
- Gradle project sync failed. Please fix your project and try again.
- 51nod 1035 最长的循环节
- 排队游戏(C程序设计进阶第3周)
- 自定义UICollectionViewFlowLayout
- HDU 1528 Card Game Cheater(打扑克)
- HDU 4328 Cut the cake(最大子矩阵+悬线法)
- USE_STDPERIPH_DRIVER, STM32F10X_HD说明
- C++实现DPM/latentSVM --- 第一篇
- SonarQube代码质量平台工具使用和介绍
- Sublime Text3破解安装
- HDU 5514 Frogs