栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

java实现按层遍历二叉树

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

java实现按层遍历二叉树

本文实例为大家分享了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 q=new linkedList();
 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 

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/139260.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号