本文實(shí)例為大家分享了java實(shí)現(xiàn)按層遍歷二叉樹(shù),按層遍歷二叉樹(shù)可以通過(guò)隊(duì)列來(lái)實(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)代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
|
import java.util.linkedlist; import java.util.queue; public class layertranverse { //按層遍歷二叉樹(shù) 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ù)插入到排序的二叉樹(shù)中 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
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/pengzhisen123/article/details/79556459