本文實例為大家分享了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
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。