Path Sum II
来源:互联网 发布:mac 桌面隐藏硬盘 编辑:程序博客网 时间:2024/06/10 16:22
Problem:
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]]
Solution: will add idea later. But this method wastes a lot spaces.
Code:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */public class Solution { ArrayList<ArrayList<Integer>> result = new ArrayList<ArrayList<Integer>>(); public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) { if (root == null) return result; helper(root, sum, new ArrayList<Integer>()); return result; } public void helper(TreeNode node, int sum, ArrayList<Integer> list) { if (node == null) return; list.add(node.val); if (node.left == null && node.right == null) { if (sum - node.val == 0) { ArrayList<Integer> tmp = new ArrayList<Integer>(list); result.add(tmp); } return; } ArrayList<Integer> listLeft = new ArrayList<Integer>(list); ArrayList<Integer> listRight = new ArrayList<Integer>(list); helper(node.left, sum - node.val, listLeft); helper(node.right, sum - node.val, listRight); }}
0 0
- LeetCode: Path Sum II
- LeetCode Path Sum II
- [Leetcode] Path Sum II
- LeetCode: Path Sum II
- Path Sum II
- [LeetCode] Path Sum II
- 【leetcode】Path Sum II
- [113]Path Sum II
- Path Sum II
- Path Sum II
- [LeetCode]Path Sum II
- Path Sum II
- Path Sum II
- [Leetcode]Path Sum II
- [leetcode]Path Sum II
- Path Sum II
- Leetcode: Path Sum II
- Path Sum II
- MATLAB nctoolbox使用
- Python 中 datetime时间模块学习
- Leetcode NO.147 Insertion Sort List
- Struts 1 之<logic>标签库
- 第330天(35W+6)
- Path Sum II
- (交叉验证 )如何实现两台Domino之间的相互访问
- 人要有所坚持,即便是有时候坚持意味着孤立无援
- Spring之配置文件加载方式
- 调试的错误就是编程给你最好的东西,因为在每个错误上面都标志着前进的一步。
- 3张图解决linux下mysql中文乱码问题
- 【深入JAVA】Java中的CPU和系统负载监控——OperatingSystemMXBean
- 网络爬虫-URL去重
- POJ-2184-01背包变形-Cow Exhibition