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]
]
Hide Tags

Tree Depth-first Search

/**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
private:
vector<vector<int> > paths;
public:
void dfs(TreeNode *node,int sum,int csum,vector<int> onePath){ //a能为引用
if(node==NULL)
return;
if(node->left==NULL && node->right==NULL){
if(node->val+csum==sum){
onePath.push_back(node->val);
paths.push_back(onePath);
}
return;
}
onePath.push_back(node->val);
dfs(node->left,sum,csum+node->val,onePath);
dfs(node->right,sum,csum+node->val,onePath);
} vector<vector<int> > pathSum(TreeNode *root, int sum) {
paths.clear();
vector<int> onePath;
dfs(root,sum,,onePath);
return paths;
}
};

最新文章

  1. 编译osgEarth2.8+VS2013+CMake3.4.0在Release版本的问题
  2. vios 虚拟光驱 安装vioc
  3. Java获取客户端IP
  4. KxMenu下拉菜单
  5. p235习题3
  6. Objective-C 【在手动内存管理中如何写set方法】
  7. #define和#undefine的用法
  8. 14.6.6 Configuring Thread Concurrency for InnoDB 配置线程并发
  9. 算法导论(第三版)Problems2(归并插入排序、数列逆序计算)
  10. {key}面向对象程序设计-C++ polymorphism 【第十三次上课笔记】
  11. centos5.5字体为方块问题的解决_深入学习编程_百度空间
  12. office web apps 部署-搭建域控服务器
  13. JustSoso笔记
  14. day13-(事务&amp;mvc&amp;反射补充)
  15. Sublime Text3 插件:DocBlockr与javascript注释规范
  16. IBM MQ 集成CXF 发送JMS 消息
  17. Dede文章标题长度修改
  18. rsync推送备份服务器(Linux)
  19. uml建模工具介绍
  20. 如何使用socket进行java网络编程(三)

热门文章

  1. 延迟对象deferred
  2. List -- 变更列表
  3. PHP+Ajax点击加载更多内容 -这个效果好,速度快,只能点击更多加载,不能滚动自动加载
  4. mysql高级教程(三)-----数据库锁、主从复制
  5. jeecms系统_自定义对象流程
  6. 基于PHP的一种Cache回调与自动触发技术
  7. TZ_10_常用的2中加密算法MD5,spring-sucrity
  8. SSM-8FastDfs搭建
  9. HDU4578 Transformation (多操作线段树)
  10. JS倒计时-毫秒