原题地址:http://oj.leetcode.com/problems/path-sum-ii/
因为题目要求要将所有符合要求的路径用一个二维数组的方式来返回,所以我们使用数据结构维护中间路径结果。
注意recursive 调用之后,要保护现场(add then remove)
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public ArrayList<ArrayList<Integer>> pathSum(TreeNode root, int sum) {
ArrayList<ArrayList<Integer>> res = new ArrayList<ArrayList<Integer>>();
if(root == null){
return res;
}
ArrayList<Integer> current = new ArrayList<Integer>();
current.add(root.val);
recursivePathSum(root,sum - root.val,current,res);
return res;
}
public void recursivePathSum(TreeNode root,int sum, ArrayList<Integer> current, ArrayList<ArrayList<Integer>> res){
if(root == null){
return;
}
if(root.left == null && root.right == null && sum ==0){
res.add(new ArrayList<Integer>(current));
return;
}
if(root.left != null){
current.add(root.left.val);
recursivePathSum(root.left,sum-root.left.val,current,res);
current.remove(current.size() -1);
}
if(root.right != null){
current.add(root.right.val);
recursivePathSum(root.right, sum-root.right.val, current,res);
current.remove(current.size() -1);
}
}
}