Lc113_路径总和 II
package com.example.demo;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
/**
* 113. 路径总和 II
* 给定一个二叉树和一个目标和,找到所有从根节点到叶子节点路径总和等于给定目标和的路径。
* <p>
* 说明: 叶子节点是指没有子节点的节点。
* <p>
* 示例:
* 给定如下二叉树,以及目标和 sum = 22,
* <p>
* 5
* / \
* 4 8
* / / \
* 11 13 4
* / \ / \
* 7 2 5 1
* 返回:
* <p>
* [
* [5,4,11,2],
* [5,8,4,5]
* ]
*/
public class Lc113 {
//将路径记录成字符串,在进行格式转换,可以考虑深拷贝
public static List<List<Integer>> pathSum(TreeNode root, int sum) {
LinkedList<String> linkedList = new LinkedList<>();
calc(root, 0, "", linkedList, sum);
linkedList.forEach(n->{
System.out.println(n);
});
List<List<Integer>> lists = new ArrayList<>();
linkedList.forEach(n->{
String[] temp = n.split(",");
List<Integer> temps =new ArrayList<>();
for (int i = 0; i < temp.length; i++) {
temps.add(Integer.valueOf(temp[i]));
}
lists.add(temps);
});
return lists;
}
public static void calc(TreeNode root, int res, String path, LinkedList<String> paths, int sum) {
if (root != null) {
path += root.val;
res += root.val;
if (root.left == null && root.right == null && res == sum) {
// System.out.println(path);
// System.out.println(res);
paths.add(path);
} else {
path += ",";
calc(root.left, res, path, paths, sum);
calc(root.right, res, path, paths, sum);
}
}
}
public static void main(String[] args) {
Integer[] arr = new Integer[]{1, 2, 3, 4, 5, 6, 7};
TreeNode root = CreateNode.createTree(arr).get(0);
pathSum(root, 7).forEach(n->{
n.forEach(m->{
System.out.println(m);
});
});
}
}
不恋尘世浮华,不写红尘纷扰
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理