题意:求和为sum的路径,将满足的所有路径返回
算法思路:首先创建一个list(用来存储所有路径),当root为null时,返回list。当该结点为叶节点并且其值为sum,则将该结点作为一条路径加入list中,返回list。从它的左孩子获取满足条件的路径,然后遍历获得的路径,将本结点加入到该路径后将该路径加入到list中。相应地从它的右孩子获得满足条件的路径,操作和前面类似,不足赘述。最后返回list。
附上代码:
//leetcode 113. Path Sum II
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> list = new ArrayList<List<Integer>>();
if(root==null)
return list;
if(root.left==null&&root.right==null&&sum-root.val==0){
List<Integer> s1 = new ArrayList<Integer>();
s1.add(root.val);
list.add(s1);
return list;
}
List<List<Integer>> l = pathSum(root.left, sum-root.val);
for(List<Integer> key:l){
key.add(0, root.val);
list.add(key);
}
List<List<Integer>> r = pathSum(root.right, sum-root.val);
for(List<Integer> key:r){
key.add(0, root.val);
list.add(key);
}
return list;
}