二叉树的前序遍历、中序遍历、后序遍历、层序遍历

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();
}
posted @   别摸我键盘  阅读(163)  评论(0编辑  收藏  举报
编辑推荐:
· 从 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)
点击右上角即可分享
微信分享提示