Leetcode-113. Path Sum II
2016-10-24 19:35
393 查看
前言:为了后续的实习面试,开始疯狂刷题,非常欢迎志同道合的朋友一起交流。因为时间比较紧张,目前的规划是先过一遍,写出能想到的最优算法,第二遍再考虑最优或者较优的方法。如有错误欢迎指正。博主首发CSDN,mcf171专栏。
中间空了一周左右没刷题,主要是参加了几次线上比赛打击略大,然后就是出差,改简历。接下来继续刷题。
博客链接:mcf171的博客
——————————————————————————————
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
return
这个题目的思路就是深度优先遍历到叶子节点,如果加和为sum则加到List里面,否则不加。Your runtime beats 16.10% of java submissions.
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
return calculatePath(results,root,sum,new ArrayList<Integer>());
}
public void calculatePath(List<List<Integer>>results, TreeNode root, int remains, List<Integer>result){
if(root!=null){
if(root.left == null && root.right == null){
if(root.val == remains){ result.add(root); results.add(result);}
}else{
remains -= root.val;
result.add(root);
if(root.right != null) calculatePath(results,root.right,remains,new ArrayList<Integer>(result));
if(root.left != null) calculatePath(results,root.left,remains,new ArrayList<Integer>(result));
}
}
}
}
中间空了一周左右没刷题,主要是参加了几次线上比赛打击略大,然后就是出差,改简历。接下来继续刷题。
博客链接:mcf171的博客
——————————————————————————————
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] ]
这个题目的思路就是深度优先遍历到叶子节点,如果加和为sum则加到List里面,否则不加。Your runtime beats 16.10% of java submissions.
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> results = new ArrayList<List<Integer>>();
return calculatePath(results,root,sum,new ArrayList<Integer>());
}
public void calculatePath(List<List<Integer>>results, TreeNode root, int remains, List<Integer>result){
if(root!=null){
if(root.left == null && root.right == null){
if(root.val == remains){ result.add(root); results.add(result);}
}else{
remains -= root.val;
result.add(root);
if(root.right != null) calculatePath(results,root.right,remains,new ArrayList<Integer>(result));
if(root.left != null) calculatePath(results,root.left,remains,new ArrayList<Integer>(result));
}
}
}
}
相关文章推荐
- leetcode- 113. Path Sum II
- [LeetCode]113. Path Sum II
- [leetcode] @python 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
- LeetCode113. Path Sum II
- Leetcode 113. Path Sum II
- leetcode 113. Path Sum II-路径和|回溯算法
- [leetcode]113. Path Sum II -- JavaScript 代码
- Leetcode 113. Path Sum II (Medium) (cpp)
- 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【java】
- [LeetCode] 113. Path Sum II