题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
ArrayList<ArrayList<Integer>> list = new ArrayList<ArrayList<Integer>>();
if(root==null){
return list;
}
helper(root, expectNumber, new ArrayList<Integer>(), 0, list);
return list;
}
public static void helper(TreeNode root, int expectNumber,
ArrayList<Integer> curList, int curSum, ArrayList<ArrayList<Integer>> list){
if(root==null){
return;
}
if(root.left ==null&& root.right==null){
if(curSum+ root.val ==expectNumber){
ArrayList<Integer> curListCopy = new ArrayList<Integer>(curList);
curListCopy.add(root.val);
list.add(curListCopy);
}
return;
}
curList.add(root.val);
curSum+=root.val;
helper(root.left, expectNumber, curList, curSum, list);
helper(root.right, expectNumber, curList, curSum, list);
curList.remove(curList.size()-1);
}
}