java實(shí)現(xiàn)按層遍歷二叉樹
本文實(shí)例為大家分享了java實(shí)現(xiàn)按層遍歷二叉樹,按層遍歷二叉樹可以通過隊(duì)列來實(shí)現(xiàn)。其主要思路如下:
1、先將根節(jié)點(diǎn)放入隊(duì)列中
2、每次都從隊(duì)列中取出一個(gè)結(jié)點(diǎn)打印該結(jié)點(diǎn)的值
3、若這個(gè)結(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í)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Java編程中的防轉(zhuǎn)義和轉(zhuǎn)義技巧匯總
在編程過程中,我們常常需要處理特殊字符和特定上下文,以確保生成的內(nèi)容在正確的環(huán)境中能夠被解析和顯示,本文將介紹一些常見的防轉(zhuǎn)義或者轉(zhuǎn)義處理的編程技巧,需要的可以參考一下2023-07-07Java?SpringBoot集成文件之如何使用POI導(dǎo)出Word文檔
這篇文章主要介紹了Java?SpringBoot集成文件之如何使用POI導(dǎo)出Word文檔,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價(jià)值,需要的朋友可以參考一下2022-08-08Java正則驗(yàn)證電話,手機(jī),郵箱,日期,金額的方法示例
這篇文章主要介紹了Java正則驗(yàn)證電話,手機(jī),郵箱,日期,金額的方法,結(jié)合具體實(shí)例形式分析了Java針對電話,手機(jī),郵箱,日期,金額的正則判定操作技巧,需要的朋友可以參考下2017-03-03Jax-rs規(guī)范REST接口文件上傳代碼實(shí)例
這篇文章主要介紹了Jax-rs規(guī)范REST接口文件上傳代碼實(shí)例,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09SpringBoot打Jar包在命令行運(yùn)行流程詳解
這篇文章主要介紹了SpringBoot打Jar包在命令行運(yùn)行流程詳解,文中通過示例代碼介紹的非常詳細(xì),對大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-09-09HTTP基本認(rèn)證(Basic Authentication)的JAVA實(shí)例代碼
下面小編就為大家?guī)硪黄狧TTP基本認(rèn)證(Basic Authentication)的JAVA實(shí)例代碼。小編覺得挺不錯(cuò)的,現(xiàn)在就分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2016-11-11Java 如何快速,優(yōu)雅的實(shí)現(xiàn)導(dǎo)出Excel
這篇文章主要介紹了Java 如何快速,優(yōu)雅的實(shí)現(xiàn)導(dǎo)出Excel,幫助大家更好的理解和學(xué)習(xí)使用Java,感興趣的朋友可以了解下2021-03-03Spring自帶定時(shí)任務(wù)@Scheduled注解實(shí)例講解
這篇文章主要介紹了Spring自帶定時(shí)任務(wù)@Scheduled注解的相關(guān)知識(shí),本文通過實(shí)例代碼給大家介紹的非常詳細(xì),感興趣的朋友跟隨小編一起看看吧2024-06-06