0%

二叉树中和为某一值的路径

题目描述

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

深度优先遍历二叉树,走到叶子结点判断一次。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
ArrayList<ArrayList<Integer>> ans = new ArrayList<>();
int target;

public ArrayList<ArrayList<Integer>> FindPath(TreeNode root, int target) {
this.target = target;
if (root == null) {
return ans;
}
getPath(root, new Stack<>());
return ans;
}

void getPath(TreeNode root, Stack<Integer> tmpPath) {
tmpPath.add(root.val);

if (root.right == null && root.left == null) {//叶子结点
int sum = 0;
ArrayList list = new ArrayList();
for (Integer i : tmpPath) {
sum += i;
list.add(list.size(), i);
}
if (sum == target) {
ans.add(list);
}
} else {
if (root.left != null) {
getPath(root.left, tmpPath);
}
if (root.right != null) {
getPath(root.right, tmpPath);
}
}
tmpPath.pop();
}