路径总和Ⅱ

113. 路径总和ii

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

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

示例 1:

img

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:

img

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

回溯

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
37
38
39
40
41
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
List<List<Integer>> ans = new ArrayList<>();
List<Integer> path = new ArrayList<>();
public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
if(root == null) return ans;
traversal(root, targetSum, root.val);
return ans;
}


public void traversal(TreeNode root, int targetSum, int sum){
path.add(root.val);
if(sum == targetSum && root.left == null && root.right == null){
ans.add(new ArrayList<>(path));
}
if(root.left != null){
traversal(root.left, targetSum, sum + root.left.val);
path.remove(path.size()-1);
}
if(root.right != null){
traversal(root.right, targetSum, sum + root.right.val);
path.remove(path.size()-1);
}

}
}

迭代(后序遍历)

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
37
38
39
class Solution {

public List<List<Integer>> pathSum(TreeNode root, int targetSum) {
List<List<Integer>> ans = new ArrayList<>(); //保存答案
List<Integer> path = new ArrayList<>();//保存当前路径

Stack<TreeNode> st = new Stack<>();
TreeNode pre = null;
//后序遍历
while(root != null || !st.isEmpty()){
while(root != null){
st.push(root);
root = root.left;
}
root = st.peek();
if(root.right == null || pre == root.right){//右节点未被访问或为空,访问该节点
if(root.left == null && root.right ==null){//遍历到叶子节点
int pathSum = 0; //记录当前路径的总和
path.clear();
for(TreeNode node : st){
pathSum += node.val;
path.add(node.val);
}

if(pathSum == targetSum){ //路径和等于目标和,加入该路径
ans.add(new ArrayList<>(path));
}
}
root = st.pop(); //访问节点出栈
pre = root;
root = null;
}else{
root = root.right;
}
}
return ans;
}

}

路径总和Ⅱ
http://example.com/2023/04/08/算法/二叉树/15. 路经总和Ⅱ/
作者
PALE13
发布于
2023年4月8日
许可协议