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

java实现二叉树的前序、中序、后序遍历(递归和非递归方式)以及层级遍历

java实现二叉树的前序、中序、后序遍历以及层级遍历

  • 一、二叉树节点定义
  • 二、递归方式
    • 1.前序遍历
    • 2.中序遍历
    • 3.后序遍历
  • 三、非递归方式
    • 1.前序遍历
    • 2.中序遍历
    • 3.后序遍历
    • 4.层级遍历
    • 5.分层打印
  • 四、测试用例

一、二叉树节点定义

class TreeNode {int val;TreeNode left;TreeNode right;TreeNode(int x) {val = x;}
}

二、递归方式

1.前序遍历

前序遍历(根-左-右)

public void preorderRecursive(TreeNode root) {if (root == null) {return;}// 访问根节点System.out.print(root.val + " ");// 递归遍历左子树preorderRecursive(root.left);// 递归遍历右子树preorderRecursive(root.right);
}

2.中序遍历

中序遍历(左-根-右)

public void inorderRecursive(TreeNode root) {if (root == null) {return;}// 递归遍历左子树inorderRecursive(root.left);// 访问根节点System.out.print(root.val + " ");// 递归遍历右子树inorderRecursive(root.right);
}

3.后序遍历

后序遍历(左-右-根)

public void postorderRecursive(TreeNode root) {if (root == null) {return;}// 递归遍历左子树postorderRecursive(root.left);// 递归遍历右子树postorderRecursive(root.right);// 访问根节点System.out.print(root.val + " ");
}

三、非递归方式

1.前序遍历

前序遍历(根-左-右)

public void preorderIterative(TreeNode root) {if (root == null) {return;}Stack<TreeNode> stack = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();System.out.print(node.val + " ");// 先压入右节点,再压入左节点,保证左节点先出栈if (node.right != null) {stack.push(node.right);}if (node.left != null) {stack.push(node.left);}}
}

2.中序遍历

中序遍历(左-根-右)

public void inorderIterative(TreeNode root) {Stack<TreeNode> stack = new Stack<>();TreeNode curr = root;while (curr != null || !stack.isEmpty()) {// 一直向左走,把所有左节点压栈while (curr != null) {stack.push(curr);curr = curr.left;}curr = stack.pop();System.out.print(curr.val + " ");// 转向右子树curr = curr.right;}
}

3.后序遍历

后序遍历(左-右-根)

public void postorderIterative(TreeNode root) {if (root == null) {return;}Stack<TreeNode> stack = new Stack<>();// 用于反转顺序Stack<Integer> output = new Stack<>();stack.push(root);while (!stack.isEmpty()) {TreeNode node = stack.pop();output.push(node.val);// 注意这里先左后右,这样输出栈的顺序就是右-左-根// 反转后就是左-右-根if (node.left != null) {stack.push(node.left);}if (node.right != null) {stack.push(node.right);}}// 输出结果while (!output.isEmpty()) {System.out.print(output.pop() + " ");}
}

4.层级遍历

层级遍历(Level Order Traversal)也称为广度优先遍历(BFS),是按层次从上到下、从左到右访问二叉树节点的遍历方式。

public void levelOrderTraversal(TreeNode root) {if (root == null) {return;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);while (!queue.isEmpty()) {TreeNode node = queue.poll();System.out.print(node.val + " ");if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}}
}

5.分层打印

分层打印的实现(按层次输出)

public void levelOrderWithLevels(TreeNode root) {if (root == null) {return;}Queue<TreeNode> queue = new LinkedList<>();queue.offer(root);int levelCount = 0;while (!queue.isEmpty()) {int levelSize = queue.size();System.out.print("Level " + (levelCount++) + ": ");for (int i = 0; i < levelSize; i++) {TreeNode node = queue.poll();System.out.print(node.val + " ");if (node.left != null) {queue.offer(node.left);}if (node.right != null) {queue.offer(node.right);}}System.out.println();}
}

四、测试用例

public static void main(String[] args) {// 构建二叉树//       1//      / \//     2   3//    / \//   4   5TreeNode root = new TreeNode(1);root.left = new TreeNode(2);root.right = new TreeNode(3);root.left.left = new TreeNode(4);root.left.right = new TreeNode(5);BinaryTreeTraversal traversal = new BinaryTreeTraversal();System.out.println("递归前序遍历:");traversal.preorderRecursive(root);System.out.println("\n非递归前序遍历:");traversal.preorderIterative(root);System.out.println("\n\n递归中序遍历:");traversal.inorderRecursive(root);System.out.println("\n非递归中序遍历:");traversal.inorderIterative(root);System.out.println("\n\n递归后序遍历:");traversal.postorderRecursive(root);System.out.println("\n非递归后序遍历:");traversal.postorderIterative(root);System.out.println("\n基本层级遍历:");traversal.levelOrderTraversal(root);System.out.println("\n\n分层打印层级遍历:");traversal.levelOrderWithLevels(root);
}

打印结果
result


文章转载自:

http://UyYZCG1n.yLtrf.cn
http://xKIqERyM.yLtrf.cn
http://WVjBLvcI.yLtrf.cn
http://GvlfkepD.yLtrf.cn
http://RlRr7rRC.yLtrf.cn
http://VGmNuUN2.yLtrf.cn
http://kdG9uhwY.yLtrf.cn
http://kzHKebv7.yLtrf.cn
http://H4OxTmCx.yLtrf.cn
http://taYU2szJ.yLtrf.cn
http://pGdVl8R8.yLtrf.cn
http://xLsQ4iyY.yLtrf.cn
http://gjgZJQOv.yLtrf.cn
http://szhUmaPG.yLtrf.cn
http://C3uIDBmg.yLtrf.cn
http://o6bLK6UF.yLtrf.cn
http://cdh8xSEq.yLtrf.cn
http://gu16pw4F.yLtrf.cn
http://DGChrjsW.yLtrf.cn
http://UEhP16Vq.yLtrf.cn
http://dHmMshV7.yLtrf.cn
http://1QT0ARYH.yLtrf.cn
http://9TpcCk0w.yLtrf.cn
http://6gRMH5oM.yLtrf.cn
http://ln5dED1R.yLtrf.cn
http://dJSnSqTE.yLtrf.cn
http://vwuNfYu3.yLtrf.cn
http://PI2YyKJ5.yLtrf.cn
http://SfoPRByE.yLtrf.cn
http://SARAmzyl.yLtrf.cn
http://www.dtcms.com/a/136864.html

相关文章:

  • Windows10系统RabbitMQ无法访问Web端界面
  • MongoDB 分账号限制数据访问
  • Stable Diffusion LoRA模型加载实现风格自由
  • 精准狙击消费者?亚马逊新受众定向功能深度测评
  • Denoising Diffusion Probabilistic Models---解析
  • virtuoso 保存PDK model过程参数方法
  • 4. k8s核心概念 pod deployment service
  • AI工具箱源码+成品网站源码+springboot+vue
  • Python基础总结(五)之字典
  • CUDA的安装
  • 多个定时器同时工作时,会出现哪些常见的bug ,如何解决??(定时任务未实时更新但刷新后正常的问题分析)
  • 数据结构和算法(七)--树
  • WPF 依赖注入启动的问题
  • shell编程之正则表达式
  • 关于Newtonsoft.Json
  • 电动硬密封耐磨球阀:工业流体控制的革新之选-耀圣
  • 碰一碰发视频源码搭建:碰一碰贴牌。碰一碰定制化开发
  • 记录一次后台项目的打包优化
  • 深度学习 从入门到精通 day_01
  • 生信小白学Rust-02
  • 用户组与用户
  • 文件包含漏洞 不同语言危险函数导致的漏洞详解
  • 我想自己组装一台服务器,微调大模型通义千问2.5 Omni 72B,但是我是个人购买,资金非常有限,最省的方案
  • PriorityQueue(优先级队列)
  • 远程游戏软件需要具备的几个基础功能和要求
  • Mysql读写分离(2)-中间件mycat和实践方案
  • Python字典及操作
  • 继承-C++
  • spring security解析
  • LeetCode 热题 100_最长递增子序列(87_300_中等_C++)(动态规划)