- 輸入一顆二叉樹和一個整數,打印出二叉樹中結點值的和爲輸入整數的全部路徑。路徑定義爲從樹的根結點開始往下一直到葉結點所通過的結點造成一條路徑。
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<Integer> list = new ArrayList<Integer>();
ArrayList<ArrayList<Integer>> ret = new ArrayList<ArrayList<Integer>>();
dfs(list, ret, root, target);
return ret;
}
public void dfs(ArrayList<Integer> list, ArrayList<ArrayList<Integer>> ret,
TreeNode root, int target) {
if(root == null) return;
list.add(root.val);
if (target == root.val && list.size() != 0 && root.left == null && root.right == null){
ret.add((ArrayList<Integer>) list.clone());
}
target -= root.val;
dfs(list, ret, root.left, target);
dfs(list, ret, root.right, target);
target += root.val;
list.remove(list.size() - 1);
}
}