LeetCode 113 Path Sum II
来源:互联网 发布:海知智能上市了吗 编辑:程序博客网 时间:2024/05/22 06:19
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]]
/** * Definition for a binary tree node. * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution2 {List<List<Integer>> result = new ArrayList<List<Integer>>();List<Integer> path = new ArrayList<Integer>();public List<List<Integer>> pathSum(TreeNode root, int sum) {dfs(root, sum);return result;}private void dfs(TreeNode root, int sum) {if (root == null) return;path.add(root.val);sum -= root.val;if (sum == 0 && root.left == null && root.right == null)/**一定要注意这里要new一个新的list,因为path在变化.**/result.add(new ArrayList<Integer>(path));path.addAll(path);dfs(root.left, sum);dfs(root.right, sum);/**因为计算新的path的时候,path要清空,所以回归的时候,把本次放进的元素移除**/path.remove(path.size() - 1);}}
0 0
- LeetCode 113: Path Sum II
- LeetCode(113)Path Sum II
- LeetCode: Path Sum II [113]
- [leetcode 113] Path Sum II
- [LeetCode 113]Path Sum II
- leetcode || 113、Path Sum II
- Leetcode[113]-Path Sum II
- Path Sum II - LeetCode 113
- 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
- 五家公司市值超2.2万亿美元!亚马逊谷歌Facebook被评“买入”,微软苹果呢?
- ABC
- 走进Scala——伴生对象(Companion Object)
- 守护进程知识及示例
- to many values to unpack
- LeetCode 113 Path Sum II
- LintCode:报数
- [Ahoi2013]作业 解题报告
- UVa 725 Division
- 六款值得推荐的android(安卓)开源框架简介
- 虚拟机安装后找不到操作系统
- 关于最短路径中的Dijkstra和Bell-man算法的区别
- 条件判断
- TCP三次握手