给定一棵二叉树和一个常数sum,求从root到叶子的路径和等于sum的路径。
public List<List<Integer>> pathSum(TreeNode root, int sum) {
List<List<Integer>> result= new LinkedList<List<Integer>>();
List<Integer> path = new LinkedList<Integer>();
if(root == null)
return result;
dfs(root, sum, path, result);
return result;
}
public void dfs(TreeNode root, int sum, List<Integer> path, List<List<Integer>> result){
if(root.left == null && root.right == null && root.val == sum){
LinkedList<Integer> currPath = new LinkedList(path); //需创建新的list,否则后面会被修改
currPath.add(root.val);
result.add(currPath);
return;
}
path.add(root.val);
if(root.left != null){
dfs(root.left, sum - root.val, path, result);
}
if(root.right != null)
dfs(root.right, sum - root.val, path, result);
path.remove(path.size() - 1); //返回时需把当前节点删除
}