题目地址:
https://www.lintcode.com/problem/binary-tree-path-sum/description
给定一棵二叉树,返回其从根到叶子所有和为target的路径。
可以用DFS+回溯。如果到了叶子,就看一下和是否是target,如果是,就加入最终结果。注意,递归回到上一层的时候需要恢复现场。代码如下:
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>> binaryTreePathSum(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, root.val, cur, res);
return res;
}
// cur存储了游走到root时路径上所有数(包含root.val)
// target即为目标和,sum代表到root为止cur里的所有数的和
private void dfs(TreeNode root, int target, int sum, List<Integer> cur, List<List<Integer>> res) {
// 如果到达了叶子并且cur里的数字和等于target,则将cur加入最终结果
if (root != null && root.left == null && root.right == null && target == sum) {
res.add(new ArrayList<>(cur));
return;
}
// 如果没到达叶子,则开始枚举两种情况:
// 如果左子树不为空,则将左子树根加入cur,并将左子树根的数加上sum传进下一层递归;如果右子树不为空也类似做
if (root.left != null) {
cur.add(root.left.val);
dfs(root.left, target, sum + root.left.val, cur, res);
cur.remove(cur.size() - 1);
}
if (root.right != null) {
cur.add(root.right.val);
dfs(root.right, target, sum + root.right.val, cur, res);
cur.remove(cur.size() - 1);
}
}
}
class TreeNode {
int val;
TreeNode left, right;
TreeNode(int val) {
this.val = val;
}
}
时间复杂度 O ( n ) O(n) O(n),空间 O ( h ) O(h) O(h)。