//给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
//
// 说明: 叶子节点是指没有子节点的节点。
//
// 示例:
//给定如下二叉树,以及目标和 sum = 22,
//
// 5
// / // 4 8
// / / // 11 13 4
// / \ / // 7 2 5 1
//
//
// 返回:
//
// [
// [5,4,11,2],
// [5,8,4,5]
//]
//
// Related Topics 树 深度优先搜索
// ?? 405 ?? 0
class Solution {
//存放每一条结果集
LinkedList<List<Integer>> ret = new LinkedList<List<Integer>>();
//存放一条路径
LinkedList<Integer> path = new LinkedList<Integer>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
dfs(root, sum);
return ret;
}
//dfs
public void dfs(TreeNode root, int sum) {
if (root == null) return;
//在该列表的末尾插入指定的元素
path.offerLast(root.val);
sum -= root.val;
//找到目标值的 叶子几点
if (root.left == null && root.right == null && sum == 0) {
//添加路径到 结果集中
ret.add(new LinkedList<Integer>(path));
}
dfs(root.left, sum);
dfs(root.right, sum);
//检索并删除此列表的最后一个元素,如果此列表为空,则返回 null
path.pollLast();
}
}
原文:https://www.cnblogs.com/nayou/p/14261969.html