Path Sum II
2015-09-09 14:21
260 查看
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
Solution:
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] ]
Solution:
/** * 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; vector<int> path; dfs(root, sum, path, res); return res; } void dfs(TreeNode* root, int sum, vector<int> &path, vector<vector<int> > &res) { if(!root) return ; int val = root->val; path.push_back(val); if(!root->left && !root->right) { if(val == sum) res.push_back(path); } dfs(root->left, sum - val, path, res); dfs(root->right, sum - val, path, res); path.pop_back(); } };
相关文章推荐
- play教程 第三课:初识play运行机制
- 使用Apache的rewrite技术
- ThinkPHP报Class 'Core\Log' not found竟然是由这个原因导致的
- hadoop2.4.1的ftpserver建立
- X509证书中RSA公钥的提取与载入
- JS闭包
- ExecutorService中submit和execute的区别
- Django的models中filter的各种用法
- linux setsid 是什么东东
- vs断点未能绑定
- 视频播放的基本原则
- 修改dbwr后台进程数量
- 修改nexus 7的boot.img,打开系统调试
- iSCSI的基础实验
- Xcode报错提示:“Info.plist couldn't be opened because there is no such file”
- 话说MOSFET的应用
- ALM11测试计划页面图解1
- 源码:从控制台接收数据
- eclipse 安装svn插件
- 简单的评价案例