leetcode113. Path Sum II
来源:互联网 发布:天下第一知乎 编辑:程序博客网 时间:2024/05/18 07:28
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 1return[ [5,4,11,2], [5,8,4,5]]
解法
DFS,判断如果是根节点,并且符合条件,则加入列表中,向上一层要把新添加的元素remove掉。
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> ret = new ArrayList<>(); List<Integer> list = new ArrayList<>(); if (root == null) { return ret; } helper(root, sum, list, ret); return ret; } public void helper(TreeNode root, int sum, List<Integer> list, List<List<Integer>> ret) { if (root == null) { return; } list.add(root.val); if (root.left == null && root.right == null && sum - root.val == 0) { ret.add(new ArrayList<Integer>(list)); list.remove(list.size() - 1); return; } else { helper(root.left, sum - root.val, list, ret); helper(root.right, sum - root.val, list, ret); } list.remove(list.size() - 1); }}
阅读全文
0 0
- LeetCode113 Path Sum II
- Leetcode113. Path Sum II
- LeetCode113:Path Sum II
- LeetCode113. Path Sum II
- LeetCode113. Path Sum II
- leetcode113~Path Sum II
- LeetCode113 Path Sum II
- leetcode113. Path Sum II
- leetcode113. Path sum II
- LeetCode113. Path Sum II
- LeetCode113—Path Sum II
- LeetCode113. Path Sum II(Medium)
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- Oracle 优化
- NGUI--三种方式监听事件
- (新)Kotlin搞起来 —— 1.Kotlin学习资料与环境配置
- linux学习文档(一)
- 利用LaTeX在双栏模板下将长公式分行
- leetcode113. Path Sum II
- linux安装tomcat
- 脚本安装vsftpd
- javaScript--arrow functions(箭头函数)解析
- QT下实现分辨率自适应的方法
- Mybatis配置文件属性讲解
- Activity生命周期实践
- Java入门学习:实现日志方法(记录代码文件名,类名,方法名,行号)
- Hadoop 集群