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] ]
Have you met this question in a real interview
思路:之前有一道PathSumd的题目,这个和之前的那个是一个思路,但是这里要把正确的路径保存到List集合中,所以稍微复杂点。深度递归,不断添加,到叶子节点的时候再不断删除添加的节点即可(不管这个路径是否满足sum,都要再删除的,满足的要找新的路径,不满足的也要找新的路径)。注意: pathList.remove(pathList.size()-1);这句不能放在叶子节点那里,必须放在最后,即遍历完左右子树,移除当前节点。
代码如下:
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<List<Integer>> resultList = new ArrayList<List<Integer>>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
sumDfs(root,sum, new ArrayList<Integer>(),0);
return resultList;
}
public void sumDfs(TreeNode root,int sum,List<Integer> pathList,int cur){
if(root==null){
return;
}else{
cur = cur+root.val;
pathList.add(root.val);
if( root.right==null && root.left==null&&cur==sum ){
ArrayList<Integer> list = new ArrayList(pathList);
resultList.add(list);
}
}
sumDfs(root.left,sum,pathList,cur);
sumDfs(root.right,sum,pathList,cur);
pathList.remove(pathList.size()-1);
}
}