当前位置: 首页 > news >正文

【java入门到放弃】二叉树

二叉树

前序中序后序遍历,是指根节点的顺序

importjava.util.LinkedList;importjava.util.Queue;publicclassBinaryTreeTraversal{// ===== 二叉树节点定义 =====staticclassTreeNode{intval;TreeNodeleft;TreeNoderight;TreeNode(intval){this.val=val;}}// ===== 创建一棵示例二叉树 =====// 1// / \// 2 3// / \// 4 5staticTreeNodebuildTree(){TreeNoderoot=newTreeNode(1);root.left=newTreeNode(2);root.right=newTreeNode(3);root.left.left=newTreeNode(4);root.left.right=newTreeNode(5);returnroot;}// ===== 1. 前序遍历:根 → 左 → 右 =====staticvoidpreorder(TreeNoderoot){if(root==null)return;System.out.print(root.val+" ");preorder(root.left);preorder(root.right);}// ===== 2. 中序遍历:左 → 根 → 右 =====staticvoidinorder(TreeNoderoot){if(root==null)return;inorder(root.left);System.out.print(root.val+" ");inorder(root.right);}// ===== 3. 后序遍历:左 → 右 → 根 =====staticvoidpostorder(TreeNoderoot){if(root==null)return;postorder(root.left);postorder(root.right);System.out.print(root.val+" ");}// ===== 4. 层序遍历(BFS) =====staticvoidlevelOrder(TreeNoderoot){if(root==null)return;Queue<TreeNode>queue=newLinkedList<>();queue.offer(root);while(!queue.isEmpty()){TreeNodenode=queue.poll();System.out.print(node.val+" ");if(node.left!=null){queue.offer(node.left);}if(node.right!=null){queue.offer(node.right);}}}// ===== main 方法测试 =====publicstaticvoidmain(String[]args){TreeNoderoot=buildTree();System.out.print("前序遍历:");preorder(root);System.out.println();System.out.print("中序遍历:");inorder(root);System.out.println();System.out.print("后序遍历:");postorder(root);System.out.println();System.out.print("层序遍历:");levelOrder(root);System.out.println();}}
http://www.cnnetsun.cn/news/134612.html

相关文章:

  • 终极指南:使用urdf-viz快速实现URDF可视化
  • 如何在10分钟内快速搭建MosDNS:打造高性能DNS转发器的完整教程
  • AI时代的思考力:程序员构建个人知识体系的完整路径!
  • 2025年大模型学习路线图:从零基础到精通,AI智能体教程带你探索LLMs与智能体AI的新世界!
  • 基于大语言模型的产量预测方法
  • 当开题报告还在“憋字”?不如让AI帮你搭好科研第一块积木
  • Upscayl终极指南:免费开源AI图像放大工具完全使用教程
  • SeaTunnel Web深度体验:企业级数据集成平台的可视化革命
  • Moonraker:简单易用的3D打印控制API服务器完整指南
  • 办公管理系统
  • Charticulator完全指南:从零开始掌握交互式图表定制
  • Netflix画质提升技巧:3步解锁4K超高清观影体验
  • Flow Launcher文件替换异常终极解决方案:从崩溃到稳定的完整修复指南
  • 3分钟快速上手:让你的电脑拥有苹果风格鼠标指针
  • 浙江比较好的港澳台联考公司有哪些
  • FF14钓鱼神器:渔人的直感5大核心功能与3分钟快速上手攻略
  • 原圈科技AI CRM系统赋能销售新未来,行业应用与创新点评
  • 原圈科技AI市场舆情分析能力深度测评——券商行业创新实践全景解读
  • 安全副业指南:漏洞挖掘 / 技术博客 / 竞赛奖金实战,有什么区别,哪个最赚钱?
  • MathLive 终极指南:2025年最简单上手的网页数学公式编辑器
  • 终极微信助手:6大智能功能让Mac微信更好用
  • 盘搜联盟 一键直达海量资源,全网最强百度网盘搜索神器!
  • 37、高效学习实践:成为学习大师
  • 网页小说自由转换神器:一键打造你的专属离线图书馆
  • 边缘AI如何真正嵌入终端?基于ESP32-S3的软硬件一体化方案详解
  • LoRA vs 全量微调:大模型微调的高效选择指南!大模型微调
  • Jellyfin Kodi插件完整安装配置教程:打造完美家庭影院体验
  • 【期末复习01_02】-结构类算法题
  • Reactor Core性能基准测试深度解析:从原理到实战的性能优化指南
  • KlipperScreen安装终极指南:零基础打造3D打印触摸屏界面