java实现按层遍历二叉树
作者:pengzhisen123 时间:2021-12-04 06:58:35
本文实例为大家分享了java实现按层遍历二叉树,按层遍历二叉树可以通过队列来实现。其主要思路如下:
1、先将根节点放入队列中
2、每次都从队列中取出一个结点打印该结点的值
3、若这个结点有子结点,则将它的子结点放入队列尾,知道队列为空。
实现代码如下:
import java.util.LinkedList;
import java.util.Queue;
public class LayerTranverse {
//按层遍历二叉树
public static void main(String[] args) {
BinaryTree1 biTree1=new BinaryTree1();
int[] data={2,8,7,4,9,3,1,6,5};
biTree1.buildTree1(data);
biTree1.layerTranverse();
}
}
class Node1{
public int data;
public Node1 left;
public Node1 right;
public Node1(int data){
this.data=data;
this.left=null;
this.right=null;
}
}
class BinaryTree1{
private Node1 root;
public BinaryTree1(){
root=null;
}
//将data数据插入到排序的二叉树中
public void insert1(int data){
Node1 newNode1=new Node1(data);
if(root==null){
root=newNode1;
}else{
Node1 current=root;
Node1 parent;
while(true){
parent=current;
if(data<current.data){
current=current.left;
if(current==null){
parent.left=newNode1;
return;
}
}else{
current=current.right;
if(current==null){
parent.right=newNode1;
return;
}
}
}
}
}
public void buildTree1(int[] data){
for(int i=0;i<data.length;i++){
insert1(data[i]);
}
}
public void layerTranverse(){
if(this.root==null){
return;
}
Queue<Node1> q=new LinkedList<Node1>();
q.add(this.root);
while(!q.isEmpty()){
Node1 n=q.poll();
System.out.print(n.data);
System.out.print(" ");
if(n.left!=null){
q.add(n.left);
}
if(n.right!=null){
q.add(n.right);
}
}
}
}
运行结果为:
2 1 8 7 9 4 3 6 5
来源:https://blog.csdn.net/pengzhisen123/article/details/79556459
标签:java,遍历,二叉树
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Springboot整合mybatis开启二级缓存的实现示例
2023-02-24 13:07:18
![](https://img.aspxhome.com/file/2023/2/81372_0s.jpg)
C语言malloc分配问题详解
2023-07-22 05:10:34
利用Spring Data MongoDB持久化文档数据的方法教程
2023-05-05 02:36:54
C#实现简单聊天程序的方法
2022-01-02 22:31:20
Unity实现跑马灯抽奖效果
2022-10-09 04:09:54
![](https://img.aspxhome.com/file/2023/4/67054_0s.jpg)
总结一次C++ 程序优化历程
2023-11-02 22:38:30
springboot对接微信支付的完整流程(附前后端代码)
2021-11-12 15:08:42
![](https://img.aspxhome.com/file/2023/4/72584_0s.png)
SpringBoot中打war包需要注意事项
2023-11-05 19:44:42
![](https://img.aspxhome.com/file/2023/6/58616_0s.png)
Java实现迅雷地址转成普通地址实例代码
2023-04-10 19:44:52
c#的dllimport使用方法详解
2023-04-20 04:01:49
C语言程序设计50例(经典收藏)
2023-07-10 08:33:19
spring schedule实现动态配置执行时间
2022-09-06 18:47:30
Spring AOP底层原理及代理模式
2023-05-05 14:19:38
C#生成漂亮验证码完整代码类
2022-06-17 14:03:33
Java异常处理机制try catch流程详解
2022-09-23 08:51:09
![](https://img.aspxhome.com/file/2023/4/62404_0s.png)
Android使用GPS获取用户地理位置并监听位置变化的方法
2022-03-29 14:24:17
![](https://img.aspxhome.com/file/2023/8/92628_0s.png)
java复制文件的4种方式及拷贝文件到另一个目录下的实例代码
2023-05-15 16:03:25
C#中foreach语句使用break暂停遍历的方法
2022-10-12 20:14:11
C#实现获取程序路径方法小结
2022-05-09 19:40:48
SpringBoot 如何实现异步编程
2023-04-15 13:45:43