题目:
题解:
先通过DFS把二叉树所有路径求出来,再从中找出符合题意的路径,时间复杂度O(N^2)。
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> pathList = new ArrayList<>();
List<Integer> currentPathList = new ArrayList<>();
getPathByDfs(root, currentPathList, pathList);
List<List<Integer>> targetPathList = new ArrayList<>();
for (List<Integer> list : pathList) {
if (list.stream().reduce(Integer::sum).get().equals(targetSum)) {
targetPathList.add(list);
}
}
return targetPathList;
}
private void getPathByDfs(TreeNode root, List<Integer> currentPathList, List<List<Integer>> pathList) {
if (root == null) {
return;
}
// 保存当前节点
currentPathList.add(root.val);
if (root.left == null && root.right == null) {
// 到达叶子节点,保存路径
pathList.add(new ArrayList<>(currentPathList));
}
getPathByDfs(root.left, currentPathList, pathList);
getPathByDfs(root.right, currentPathList, pathList);
// 回溯
currentPathList.remove(currentPathList.size() - 1);
}