题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
要注意java默认是浅拷贝,需要copy.addAll(list);不然结果会为空
另外 list.remove(list.size()-1);删除末尾不需要的元素
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 {
ArrayList<ArrayList<Integer>> res = new ArrayList<>();
ArrayList<Integer> list = new ArrayList<>();
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int expectNumber) {
if(root == null) return res;
list.add(root.val);
expectNumber = expectNumber - root.val;
if(expectNumber == 0 && root.left == null && root.right == null) {
ArrayList<Integer> copy = new ArrayList<>();
copy.addAll(list);
res.add(copy);
}
FindPath(root.left,expectNumber);
FindPath(root.right,expectNumber);
list.remove(list.size()-1);
return res;
}
}