题目描述

给你二叉树的根节点 root 和一个整数目标和 targetSum ,找出所有 从根节点到叶子节点 路径总和等于给定目标和的路径。

叶子节点 是指没有子节点的节点。

示例 1:

1
2
输入:root = [5,4,8,11,null,13,4,7,2,null,null,5,1], targetSum = 22
输出:[[5,4,11,2],[5,8,4,5]]

示例 2:

1
2
输入:root = [1,2,3], targetSum = 5
输出:[]

示例 3:

1
2
输入:root = [1,2], targetSum = 0
输出:[]

提示:

  • 树中节点总数在范围 [0, 5000]
  • -1000 <= Node.val <= 1000
  • -1000 <= targetSum <= 1000

注意:本题与主站 113 题相同:https://leetcode-cn.com/problems/path-sum-ii/

解法

  • 回溯+状态记录
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
36
import leetcode.TreeNode;

import java.util.LinkedList;
import java.util.List;

class Solution {
/**
* 回溯+状态记录
* @param root
* @param target
* @return
*/
LinkedList<Integer> path=new LinkedList<>();
LinkedList<List<Integer>> res=new LinkedList<>();
public List<List<Integer>> pathSum(TreeNode root, int target) {
toFlashBack(root, target);
return res;
}
public void toFlashBack(TreeNode root,int target){
//1.递归终止条件,到叶节点
if (root==null){
return;
}
//2.当前节点入队,目标值减去当前节点值,判断是否为结果
path.add(root.val);
target-=root.val;
if (target==0&&root.left==null&&root.right==null){
res.add(new LinkedList<>(path));
}
//3.左右递归
toFlashBack(root.left, target);
toFlashBack(root.right, target);
//4.进行回溯返回上一状态
path.removeLast();
}
}
  • 时间复杂度:O(n)

来源:力扣(LeetCode)
链接:剑指 Offer 34. 二叉树中和为某一值的路径 - 力扣(LeetCode)