您的位置:首页 > 编程语言 > Java开发

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 
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));
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode 算法