发布于 

剑指 Offer.34-二叉树中和为某一值的路径

剑指 Offer.34-二叉树中和为某一值的路径

题目链接

<二叉树中和为某一值的路径>

问题描述

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

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

个人想法

深度优先搜索 + 回溯

代码

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
class Solution {
List<List<Integer>> res = new LinkedList<>();
LinkedList<Integer> subres = new LinkedList<>();

public List<List<Integer>> pathSum(TreeNode root, int target) {
dfs(root,target);
return res;
}

//深度优先搜索方法
void dfs(TreeNode root,int target){
if(root == null){
//当搜索到底部时 返回结果
return;
}

//加入路径
subres.add(root.val);

//根据题意 最终的结尾节点必须为叶子节点,需要通过条件判断其为叶子节点
if((target-root.val) == 0 && root.left == null && root.right == null){
//找到对应解,进行存储
res.add(new LinkedList(subres));
}

dfs(root.left,target-root.val);
dfs(root.right,target-root.val);

//还原现场
subres.removeLast();

}
}

注意点

在将可行路径加入解集中,需要判断当前节点是否是叶子节点,并且在加入解集合时,需要使用res.add(new LinkedList(subres))对当前的解进行拷贝,否则路径集合会被递归修改至两个空集合


本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。

本站由 @John Doe 创建,使用 Stellar 作为主题。