LeetCode 113. Path Sum II(java)
2018-03-07 09:45
387 查看
Given a binary tree and a sum, find all root-to-leaf paths where each path’s sum equals the given sum.
recursion解法,树的解法比较固定,分为base case和recursion rule,然后定好参数,在需要的时候调用自身即可。
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] ]
recursion解法,树的解法比较固定,分为base case和recursion rule,然后定好参数,在需要的时候调用自身即可。
public List<List<Integer>> pathSum(TreeNode root, int sum) { List<List<Integer>> res = new ArrayList<>(); if (root == null) { return res; } helper(res, root, new ArrayList<Integer>(), sum); return res; } public void helper(List<List<Integer>> res, TreeNode root, ArrayList<Integer> path, int sum) { //base case: leaf if (root.left == null && root.right == null) { if (root.val == sum) { path.add(root.val); res.add(new ArrayList<Integer>(path)); path.remove(path.size() - 1); } return; } //recursion rule: non-leaf path.add(root.val); if (root.left != null) helper(res, root.left, path, sum - root.val); if (root.right != null) helper(res, root.right, path, sum - root.val); path.remove(path.size() - 1); return; }
相关文章推荐
- 【leetcode】113. Path Sum II【java】
- 【LeetCode】113. Path Sum II 基于Java和C++的解法及分析
- Path Sum II leetcode java
- Leetcode 113. Path Sum II
- Leetcode 113. Path Sum II
- 2017.10.29 LeetCode - 113. Path Sum II【DFS的运用】【补】
- LeetCode力扣之113. Path Sum II
- [LeetCode]112. Path Sum&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 DFS深度优先遍历
- [leetcode]113. Path Sum II -- JavaScript 代码
- [LeetCode]113. Path Sum II(列出二叉树根到叶路径和等于sum的所有路径)
- LeetCode 113. Path Sum II DFS求解
- [leetcode] 113. Path Sum II 解题报告