服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java实现按层遍历二叉树

java实现按层遍历二叉树

2021-06-28 09:49pengzhisen123 Java教程

这篇文章主要为大家详细介绍了java实现按层遍历二叉树,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

本文实例为大家分享了java实现按层遍历二叉树,按层遍历二叉树可以通过队列来实现。其主要思路如下:

1、先将根节点放入队列中

2、每次都从队列中取出一个结点打印该结点的值

3、若这个结点有子结点,则将它的子结点放入队列尾,知道队列为空。

实现代码如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
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

延伸 · 阅读

精彩推荐