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

求路径的和与某一特定的值时候对等即可,简单的dfs,代码如下:

 class Solution {
public:
vector<vector<int>> pathSum(TreeNode* root, int sum) {
vector<int> res;
dfs(root, res, sum);
return ret;
} void dfs(TreeNode * root, vector<int> res, int left)
{
if(!root) return;
if(!root->left && !root->right && left == root->val){
res.push_back(root->val);
ret.push_back(res);
}
if(left <= root->val)
return;
else{
res.push_back(root->val);
if(root->left)
dfs(root->left, res, left -= root->val);
if(root->right)
dfs(root->right, res, left -= root->val);
}
}
private:
vector<vector<int>> ret;
};

java版本代码如下,方法相同,就是java的引用处理起来稍微麻烦点,递归尾部应该pop一下。

 public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> ret = new ArrayList<List<Integer>>();
Stack<Integer> tmp = new Stack<Integer>();
dfs(ret, tmp, root, sum);
return ret;
} public void dfs(List<List<Integer>> ret, Stack<Integer> tmp, TreeNode root, int remain){
if(root == null) return;
tmp.push(root.val);
if(root.left == null && root.right == null)
if(remain == root.val)
ret.add((Stack<Integer>)tmp.clone());
if(root.left != null) dfs(ret, tmp, root.left, remain - root.val);
if(root.right != null) dfs(ret, tmp, root.right, remain - root.val);
tmp.pop();
}
}

最新文章

  1. CALayer的transform属性
  2. 欧拉回路(hdu3018)
  3. ListView实现Item局部刷新
  4. leetcode-Single Number III 找独数
  5. opencv笔记4:模板运算和常见滤波操作
  6. log4Net 简单配置实用
  7. Nginx - Additional Modules, About Your Visitors
  8. Android Game
  9. [转]MVC模式已死?何不试试MOVE
  10. 使用ActionBar实现Tab导航(快速生成Tab样式)
  11. Mac下MAMP初试体验
  12. 笔试题&amp;amp;面试题:CW输出矩阵
  13. Unity进阶----AssetBundle_03(2018/11/07)
  14. centos官网下载地址
  15. C语言数组一种巧妙的使用方式
  16. PCL点云配准(3)
  17. 转发-基于ASP.NET MVC 4/5 Razor的模块化/插件式架构实现
  18. 2017-5-19&amp;5-23/系统性能指标
  19. yii2 HTML组手
  20. Kafka集群副本分配算法解析

热门文章

  1. (2)linux未使用eth0,未使用IPV4导致无法连接
  2. IDEA中创建maven web项目的详细部署
  3. 002-JVM运行时数据区【内存模型】
  4. 虚拟化qemu-img的简单用法。
  5. django的模板系统过滤器笔记
  6. 剑指offer 面试28题
  7. 动手动脑:String.equals()的使用方法
  8. java的服务端与客户端通信(2)
  9. Java技术路线
  10. Nginx配置中last和break及permanent和redirect的区别