【剑指Offer】二叉树中和为某一值的路径

题目

输入一棵二叉树和一个整数,打印出二叉树中结点值的和为输入整数的所有路径。从树的根结点开始往下一直到叶结点所经过的结点形成一条路径。

实现

1
2
3
4
5
6
7
8
9
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;

public TreeNode(int val) {
this.val = val;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
ArrayList<ArrayList<Integer>> paths = new ArrayList<>();
ArrayList<Integer> path = new ArrayList<>();

FindPath(root, target, 0, path, paths);

return paths;
}

private void FindPath(TreeNode root, int target, int sum, ArrayList<Integer> path, ArrayList<ArrayList<Integer>> paths) {
if (root == null)
return;

int currentSum = sum + root.val;
path.add(root.val);

if (currentSum == target && root.left == null && root.right == null)
paths.add(new ArrayList(path));

FindPath(root.left, target, currentSum, path, paths);
FindPath(root.right, target, currentSum, path, paths);

path.remove(path.size() - 1);
}