Leetcode 113. Path Sum II
来源:互联网 发布:40岁程序员干不了 编辑:程序博客网 时间:2024/06/13 17:31
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]]
解法一:
注意要弹出最后一个数。
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) return res; List<Integer> path = new ArrayList<>(); path.add(root.val); dfs(root, sum - root.val, path, res); return res; } private void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) { if (root == null) return; if (root.left == null && root.right == null && sum == 0) { res.add(new ArrayList<Integer>(path)); return; } if (root.left != null) { path.add(root.left.val); dfs(root.left,sum-root.left.val,path,res); path.remove(path.size() - 1); } if (root.right != null) { path.add(root.right.val); dfs(root.right,sum-root.right.val,path,res); path.remove(path.size() - 1); } }}
解法二:
这个看起来比较简单。
pathSum:
1、如果是null, 就返回
2、把当前node的值加到ArrayList里
3、如果当前节点是叶节点且等于余下的值时,加入res中
4、用归递左边和右边的节点
5、注意要去掉最后一个左叶节点才可以继续右叶节点
public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<List<Integer>>(); pathSum(root, sum, new ArrayList<Integer>(), res); return res; } void pathSum(TreeNode root, int sum, List<Integer> path, List<List<Integer>> res) { if (root == null) { return; } path.add(root.val); if (root.left == null && root.right == null && sum == root.val) { res.add(new ArrayList<Integer>(path)); } else { pathSum(root.left, sum - root.val, path, res); pathSum(root.right, sum - root.val, path, res); } path.remove(path.size() - 1); }}
0 0
- LeetCode 113. Path Sum II
- [LeetCode]113.Path Sum II
- [Leetcode] 113. Path Sum II
- [leetcode] 113.Path Sum II
- [LeetCode]113. Path Sum II
- LeetCode: 113. Path Sum II
- leetcode 113. Path Sum II
- 113. Path Sum II LeetCode
- leetcode 113. Path Sum II
- LeetCode *** 113. Path Sum II
- Leetcode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode 113. Path Sum II
- LeetCode - 113. Path Sum II
- Leetcode 113. Path Sum II
- [LeetCode] 113. Path Sum II
- [leetcode] 113. Path Sum II
- [LeetCode] 113. Path Sum II
- Redis实现简单消息队列
- java project单独使用hibernate
- wordpress <4.6.1 语言文件导致的代码执行
- 在Linux操作系统下安装JAVA8
- 如果你没想好要不要做程序媛
- Leetcode 113. Path Sum II
- 【CSS/JS学习】如何实现单行/多行文本溢出的省略(...)
- 代码自动生成.编程语言
- 支持向量机中相关问题思考
- 360极速浏览器和360chrome首页设置加密算法
- LintCode : 翻转链表
- java基础--类与对象(会不断更新)
- 第二章:java基础语法(java知识点)
- 集合相似度