java實現(xiàn)按層遍歷二叉樹
更新時間:2019年01月05日 11:16:03 作者:pengzhisen123
這篇文章主要為大家詳細介紹了java實現(xiàn)按層遍歷二叉樹,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java實現(xiàn)按層遍歷二叉樹,按層遍歷二叉樹可以通過隊列來實現(xiàn)。其主要思路如下:
1、先將根節(jié)點放入隊列中
2、每次都從隊列中取出一個結點打印該結點的值
3、若這個結點有子結點,則將它的子結點放入隊列尾,知道隊列為空。
實現(xiàn)代碼如下:
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數(shù)據(jù)插入到排序的二叉樹中
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
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
Java?SpringBoot集成文件之如何使用POI導出Word文檔
這篇文章主要介紹了Java?SpringBoot集成文件之如何使用POI導出Word文檔,文章圍繞主題展開詳細的內(nèi)容介紹,具有一定的參考價值,需要的朋友可以參考一下2022-08-08
HTTP基本認證(Basic Authentication)的JAVA實例代碼
下面小編就為大家?guī)硪黄狧TTP基本認證(Basic Authentication)的JAVA實例代碼。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2016-11-11
Java 如何快速,優(yōu)雅的實現(xiàn)導出Excel
這篇文章主要介紹了Java 如何快速,優(yōu)雅的實現(xiàn)導出Excel,幫助大家更好的理解和學習使用Java,感興趣的朋友可以了解下2021-03-03

