题解 | #二叉树根节点到叶子节点和为指定值的路径#
二叉树根节点到叶子节点和为指定值的路径
http://www.nowcoder.com/practice/840dd2dc4fbd4b2199cd48f2dadf930a
import java.util.*;
/*
* public class TreeNode {
* int val = 0;
* TreeNode left = null;
* TreeNode right = null;
* }
*/
public class Solution {
/**
*
* @param root TreeNode类
* @param sum int整型
* @return int整型ArrayList<ArrayList<>>
*/
public ArrayList<ArrayList<Integer>> pathSum (TreeNode root, int sum) {
// write code here
ArrayList<ArrayList<Integer>> outerList = new ArrayList<>();
ArrayList<Integer> innerList = new ArrayList<>();
if(root == null){
return outerList;
}
int hasSum = 0;
dfs(root, outerList, innerList, hasSum, sum);
return outerList;
}
public void dfs(TreeNode root, ArrayList<ArrayList<Integer>> outerList, ArrayList<Integer> innerList, int hasSum, int total){
hasSum += root.val;
innerList.add(root.val);
if(hasSum == total && root.left == null && root.right == null){
outerList.add(new ArrayList<>(innerList));
}
if(root.left != null){
// 必须要传副本过去
dfs(root.left, outerList, new ArrayList<>(innerList), hasSum, total);
}
if(root.right != null){
dfs(root.right, outerList, new ArrayList<>(innerList), hasSum, total);
}
}
} 
滴滴公司福利 1726人发布