题目地址:
https://www.lintcode.com/problem/binary-tree-path-sum-ii/description
给定一棵二叉树,再给定一个数字target,求其所有从上到下和等于target的路径。
思路是递归,用一个列表存储从树根到当前节点的路径,然后每次遍历到一个节点的时候,就考察这个列表有没有一个后缀的和是target,然后把这个后缀分离出来加进最终结果即可。注意的是,这里的DFS到下一层返回的时候,要回溯,删去最后一个元素(当然这也取决于具体实现)。代码如下:
import java.util.ArrayList;
import java.util.List;
public class Solution {
/*
* @param root: the root of binary tree
* @param target: An integer
* @return: all valid paths
*/
public List<List<Integer>> binaryTreePathSum2(TreeNode root, int target) {
// write your code here
List<List<Integer>> res = new ArrayList<>();
if (root == null) {
return res;
}
List<Integer> cur = new ArrayList<>();
cur.add(root.val);
dfs(root, target, cur, res);
return res;
}
// cur存储的是从树根到当前节点root路径上的所有数字
private void dfs(TreeNode root, int target, List<Integer> cur, List<List<Integer>> res) {
if (root == null) {
return;
}
// 算其后缀,如果等于target就加入最终结果
int sum = 0;
for (int i = cur.size() - 1; i >= 0; i--) {
sum += cur.get(i);
if (sum == target) {
res.add(new ArrayList<>(cur.subList(i, cur.size())));
}
}
if (root.left != null) {
cur.add(root.left.val);
dfs(root.left, target, cur, res);
cur.remove(cur.size() - 1);
}
if (root.right != null) {
cur.add(root.right.val);
dfs(root.right, target, cur, res);
cur.remove(cur.size() - 1);
}
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n h ) O(nh) O(nh),事实上每遍历到第 h h h层的时候就需要 O ( h ) O(h) O(h)的时间计算一下后缀和,所以时间复杂度是 O ( n h ) O(nh) O(nh);空间 O ( h ) O(h) O(h)。