题目
输入一棵二叉树和一个整数,打印出二叉树中节点值的和为输入整数的所有路径。从树的根节点开始往下一直到叶节点所经过的节点形成一条路径。
示例:
给定如下二叉树,以及目标和 sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ / \
7 2 5 1
返回:
[
[5,4,11,2],
[5,8,4,5]
]
提示:
节点总数 <= 10000
解题思路
回溯思想
深度优先搜索,从根节点一路走到头,依次加入路径并计算剩余目标和,直到走完,若目标和为0并且走到叶子节点不能再走判定次路径为结果集中的一条满足路径。
代码
class Solution {
//单条路径集合
private LinkedList<Integer> ans = new LinkedList<>();
//所有满足路径的集合
private LinkedList<List<Integer>> answer = new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int sum) {
pre(root, sum);
return answer;
}
public void pre(TreeNode root, int sum) {
if (root == null) {
return;
}
//加入当前节点
sum -= root.val;
ans.add(root.val);
if (sum == 0 && root.left == null && root.right == null) {
//拷贝一份ans 浅拷贝
LinkedList<Integer> temp = (LinkedList<Integer>) ans.clone();
answer.add(temp);
}
pre(root.left, sum);
pre(root.right, sum);
//回溯
ans.removeLast();
}
}