欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

java實(shí)現(xiàn)按層遍歷二叉樹

 更新時(shí)間:2019年01月05日 11:16:03   作者:pengzhisen123  
這篇文章主要為大家詳細(xì)介紹了java實(shí)現(xiàn)按層遍歷二叉樹,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下

本文實(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)文章

最新評論