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