Given a binary tree and a sum, find all root-to-leaf paths where each path's sum equals the given sum.
For example:Given the below binary tree and
sum = 22
,
5 / \ 4 8 / / \ 11 13 4 / \ / \ 7 2 5 1
return
[ [5,4,11,2], [5,8,4,5] ]
跟第一题比较的话,不再仅仅追求是否存在这样的路径,而是要求得到所有符合条件的路径,那么我们就要保存这些路径,该怎么保存这样的路径呢。开始考虑采用迭代的方式,这样就可以采用全局变量来存储符合条件的路径,但是感觉也不好求(主要是自己不擅长将一个递归转换成迭代方式,每一次转换,都是错误百出,要调试多次,才能转换妥当,不过记得在一道题说,递归在实际中是不用的),所以就使用list,由于list是对象,而在函数之间传递对象时使用对象的地址传递,故也就起到了全局变量的作用。因此有了下面的算法。思路还是很简单的,不过在处理path的处理,在inorder里添加了一个节点,递归到上一个节点时还需要删除这个节点(由于path是一个"全局变量",会影响在其他函数中的使用),只要处理好了add和remove的时刻就OK了,其他的就是一个DFS过程。
/**
* Definition for binary tree
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new ArrayList<List<Integer>>();//用来记录全局结果
List<TreeNode> path = new ArrayList<TreeNode>();//记录走过的路径
if(root != null){
inorder(root,list,path,0,sum);
}
return list;
}
public void inorder(TreeNode root,List<List<Integer>> list,List<TreeNode> path,int value , int sum){
if(root.left == null && root.right == null){//叶子节点
if(root.val + value == sum){//找到了,复制路径,此时path里都是符合题意的节点
List<Integer> tmp = new ArrayList<Integer>();
for(int i =0; i < path.size();i++){
tmp.add(path.get(i).val);
}
tmp.add(root.val);
list.add(tmp);
}
}else{//非叶子节点
boolean flag = false;
if(root.left != null){
path.add(root);
inorder(root.left,list,path,value+root.val,sum);
flag = true;
}
if(root.right != null){
if(flag){//true,说明root在路径里,不重复添加
inorder(root.right,list,path,value+root.val,sum);
}else{//root不在路径里
path.add(root);
inorder(root.right,list,path,value+root.val,sum);
}
}
path.remove(root);
}
}
}
Runtime: 284 ms