本文實(shí)例為大家分享了java實(shí)現(xiàn)按層遍歷二叉樹,按層遍歷二叉樹可以通過隊(duì)列來實(shí)現(xiàn)。其主要思路如下:

創(chuàng)新互聯(lián)公司-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比昭陽網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式昭陽網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋昭陽地區(qū)。費(fèi)用合理售后完善,10多年實(shí)體公司更值得信賴。
1、先將根節(jié)點(diǎn)放入隊(duì)列中
2、每次都從隊(duì)列中取出一個結(jié)點(diǎn)打印該結(jié)點(diǎn)的值
3、若這個結(jié)點(diǎn)有子結(jié)點(diǎn),則將它的子結(jié)點(diǎn)放入隊(duì)列尾,知道隊(duì)列為空。
實(shí)現(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);
}
}
}
}
運(yùn)行結(jié)果為:
2 1 8 7 9 4 3 6 5
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
當(dāng)前題目:java實(shí)現(xiàn)按層遍歷二叉樹
本文URL:http://chinadenli.net/article46/iidheg.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、全網(wǎng)營銷推廣、網(wǎng)頁設(shè)計公司、企業(yè)網(wǎng)站制作、ChatGPT、企業(yè)建站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)