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 andsum = 22,

              5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1

return

[
[5,4,11,2],
[5,8,4,5]
] 题意:给定一数,在树中找出所有路径和等于该数的情况。
方法一:
使用vector向量实现stack的功能,以方便输出指定路径。思想和代码和Path sum大致相同。
/**
* Definition for binary tree
* 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<TreeNode *> vec;
TreeNode *pre=NULL;
TreeNode *cur=root;
int temVal=; while(cur|| !vec.empty())
{
while(cur)
{
vec.push_back(cur);
temVal+=cur->val;
cur=cur->left;
}
cur=vec.back();
if(cur->left==NULL&&cur->right==NULL&&temVal==sum)
{ //和Path sum最大的区别
vector<int> temp;
for(int i=;i<vec.size();++i)
temp.push_back(vec[i]->val);
res.push_back(temp);
}
if(cur->right&&cur->right !=pre)
cur=cur->right;
else
{
vec.pop_back();
temVal-=cur->val;
pre=cur;
cur=NULL;
} }
return res;
}
};

方法二:递归法

/**
* Definition for binary tree
* 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;
findPaths(root,sum,res,path);
return res;
}
void findPaths(TreeNode *root,int sum,vector<vector<int>> &res,vector<int> &path)
{
if(root==NULL) return;
path.push_back(root->val);
if(root->left==NULL&&root->right==NULL&&sum==root->val)
res.push_back(path); findPaths(root->left,sum-root->val,res,path);
findPaths(root->right,sum-root->val,res,path);
path.pop_back();
}
};
												

最新文章

  1. 配置 nginx server 出现nginx: [emerg] &quot;root&quot; directive is duplicate in /etc/nginx/server/blogs.conf:7
  2. poj 3159 Candies 差分约束
  3. 批量修改照片名称的shell脚本
  4. C#_字符串的操作
  5. 例题6-7 Trees on the level ,Uva122
  6. Nginx下载服务生产服务器调优
  7. initMethod 和 afterPropertiesSet 以及 AwareMethod方法的执行时机
  8. 帝国cms栏目死变量
  9. MySQL filesort优化案例一则
  10. 根据NSString字符串长度自动改变UILabel的frame
  11. Ubuntu14.04安装有道词典
  12. (笔记):组合and继承之访问限制(一)
  13. Django学习目录
  14. java中的HMAC-SHA1加密
  15. 虚函数 error LNK2001: 无法解析的外部符号 &quot;public: virtual void __cdecl
  16. &lt;ROS&gt; NodeHandle句柄
  17. JWT 认证 以及Django 中的应用
  18. 华硕R系列的解剖图
  19. Microsoft JET Database Engine 错误 &#39;80004005&#39; 未指定错误
  20. ElasticSearch入门 第四篇:使用C#添加和更新文档

热门文章

  1. h5移动端页面meta标签
  2. CentOS(Linux)安装KETTLE教程 并配置执行定时任务
  3. Python3 使用基本循环实现多级目录(思路)
  4. WRITE
  5. 販売管理(SD)
  6. node 发送 post 请求 get请求。
  7. Qt Qwdget 汽车仪表知识点拆解3 进度条编写
  8. mysql 5.7.18 源码安装笔记
  9. weblogic中配置自定义filter和servlet
  10. C++ STL容器——stack用法介绍