题解 | #二叉树中和为某一值的路径(二)#
二叉树中和为某一值的路径(二)
http://www.nowcoder.com/practice/b736e784e3e34731af99065031301bca
dfs
1.要有明确的结束dfs的标志
2.回溯的时候,要恢复现场
import java.util.ArrayList;
/**
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root,int sum) {
ArrayList<ArrayList<Integer>> ret = new ArrayList<>();
if(root != null)
dfs(root,sum,ret,new ArrayList<Integer>(),0);
return ret;
}
public void dfs(TreeNode node,int sum,ArrayList<ArrayList<Integer>> ret,ArrayList<Integer> list,int cur){
cur += node.val;
list.add(node.val);
if(cur == sum && node.left == null && node.right == null){
ArrayList<Integer> ele = new ArrayList<>(list);
ret.add(ele);
}
if(node.left != null){
dfs(node.left,sum,ret,list,cur);
}
if(node.right != null){
dfs(node.right,sum,ret,list,cur);
}
list.remove(list.size() - 1);
cur -= node.val;
}
}