题目链接 : https://leetcode-cn.com/problems/path-sum-ii/

题目描述:

给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。

说明: 叶子节点是指没有子节点的节点。

示例:

给定如下二叉树,以及目标和 sum = 22,

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

返回:

[
[5,4,11,2],
[5,8,4,5]
]

思路:

和上一题一样, 用DFS只不过在遍历时候,要记录val而已

def pathSum(self, root: TreeNode, sum: int) -> List[List[int]]:
res = []
if not root: return []
def helper(root,sum, tmp):
if not root:
return
if not root.left and not root.right and sum - root.val == 0 :
tmp += [root.val]
res.append(tmp)
return
helper(root.left, sum - root.val, tmp + [root.val])
helper(root.right, sum - root.val, tmp + [root.val])
helper(root, sum, [])
return res

java

class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> res = new ArrayList<>();
helper(root, sum, res, new ArrayList<Integer>());
return res;
} private void helper(TreeNode root, int sum, List<List<Integer>> res, ArrayList<Integer> tmp) {
if (root == null) return;
tmp.add(root.val);
if (root.left == null && root.right == null && sum - root.val == 0) res.add(new ArrayList<>(tmp));
helper(root.left, sum - root.val, res, tmp);
helper(root.right, sum - root.val, res, tmp);
tmp.remove(tmp.size() - 1);
}
}

相关题型 : 112. 路径总和

最新文章

  1. UVA-11997 K Smallest Sums
  2. phpstrom 10 激活
  3. CSS3知识点总结----属性选择器
  4. mysql +ibatis
  5. cuda 初学大全
  6. GoldenGate 配置extract,replicat进程自启动
  7. php Curl_setop 的学习
  8. BLE-NRF51822教程17-DFU使用手机升级
  9. android 表情,软键盘冲突解决方案(仿微博等SNS应用)
  10. .NET之RabbitMQ学习笔记(二)-安装
  11. linux下数据同步、回写机制分析
  12. 2.QT中使用资源文件,程序打包
  13. vmware(1):vmware中的bridge、nat、host-only的区别
  14. TreeMap 的排序冲突吗
  15. note 9 列表、时间复杂度、排序
  16. c/c++ new delete初探
  17. Oracle使用笔记(三)
  18. spring部分注解
  19. Ubuntu yindaoxiufu 引导修复(Boot Repair)
  20. Python 编程快速上手 第十四章 处理 CSV 文件和 JSON 数据

热门文章

  1. winform 皮肤
  2. html article标签 语法
  3. JAVA支持HTTP断点续传
  4. C++ 打印XPS文档
  5. Task的用法
  6. jenkins 打标签实现回滚
  7. Spring Security 报There is no PasswordEncoder mapped for the id &quot;null&quot;
  8. MySQL技术内幕 InnoDB存储引擎 之 InnoDB体系架构
  9. python编译报错
  10. 四十、python中的生成器和迭代器