二叉树的前序遍历、中序遍历、后序遍历、层序遍历
1.节点定义
public class TreeNode {
public int val;
public TreeNode left;
public TreeNode right;
public TreeNode(int val) {
this.val = val;
}
public TreeNode(int val, TreeNode left, TreeNode right) {
this.val = val;
this.left = left;
this.right = right;
}
}
2.中序遍历
左-根-右
public static void printTreeInOrder(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
printTreeInOrder(root.left);
}
System.out.print(root.val + "\t");
if (root.right != null) {
printTreeInOrder(root.right);
}
}
3.先序遍历
根-左-右
public static void printTreePreOrder(TreeNode root) {
if (root == null) {
return;
}
System.out.print(root.val + "\t");
if (root.left != null) {
printTreePreOrder(root.left);
}
if (root.right != null) {
printTreePreOrder(root.right);
}
}
4.后序遍历
左-右-根
public static void printTreePostOrder(TreeNode root) {
if (root == null) {
return;
}
if (root.left != null) {
printTreePostOrder(root.left);
}
if (root.right != null) {
printTreePostOrder(root.right);
}
System.out.print(root.val + "\t");
}
5.层序遍历
利用队列
public static void printTreeLevelOrder(TreeNode root) {
LinkedList<TreeNode> queue = new LinkedList<>();
queue.offer(root);
while (!queue.isEmpty()) {
TreeNode current = queue.poll();
System.out.print(current.val + "\t");
if (current.left != null) {
queue.offer(current.left);
}
if (current.right != null) {
queue.offer(current.right);
}
}
System.out.println();
}
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)