news 2026/6/13 9:01:31

【java入门到放弃】二叉树

作者头像

张小明

前端开发工程师

1.2k 24
文章封面图
【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();}}
版权声明: 本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:809451989@qq.com进行投诉反馈,一经查实,立即删除!
网站建设 2026/6/12 5:31:32

FF14智能钓鱼计时器:渔人的直感完整使用手册

FF14智能钓鱼计时器&#xff1a;渔人的直感完整使用手册 【免费下载链接】Fishers-Intuition 渔人的直感&#xff0c;最终幻想14钓鱼计时器 项目地址: https://gitcode.com/gh_mirrors/fi/Fishers-Intuition 还在为FF14钓鱼时错过关键时机而烦恼吗&#xff1f;渔人的直感…

作者头像 李华
网站建设 2026/6/12 6:03:54

构建软件测试中的伦理风险识别与评估体系

在人工智能与大数据技术蓬勃发展的今天&#xff0c;软件测试已从单纯的功能验证转向更广阔的责任疆域。根据Gartner 2024年预测&#xff0c;到2027年&#xff0c;未能建立系统化伦理风险评估机制的企业将面临30%以上的合规处罚风险。软件测试从业者作为产品质量的重要把关者&am…

作者头像 李华
网站建设 2026/6/12 20:29:44

OpenBoardView终极指南:快速掌握电路板文件查看技巧

OpenBoardView终极指南&#xff1a;快速掌握电路板文件查看技巧 【免费下载链接】OpenBoardView View .brd files 项目地址: https://gitcode.com/gh_mirrors/op/OpenBoardView 想要高效查看和分析电路板设计文件吗&#xff1f;OpenBoardView作为一款功能强大的开源软件…

作者头像 李华
网站建设 2026/6/12 13:50:40

X-AnyLabeling完整使用指南:从零开始掌握AI数据标注

X-AnyLabeling完整使用指南&#xff1a;从零开始掌握AI数据标注 【免费下载链接】X-AnyLabeling Effortless data labeling with AI support from Segment Anything and other awesome models. 项目地址: https://gitcode.com/gh_mirrors/xa/X-AnyLabeling X-AnyLabelin…

作者头像 李华