-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTreeBFS.java
More file actions
35 lines (27 loc) Β· 823 Bytes
/
TreeBFS.java
File metadata and controls
35 lines (27 loc) Β· 823 Bytes
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
package basic.bfs;
import basic.algorithm.AbstractTreeAlogorithm;
import java.util.LinkedList;
import java.util.Queue;
public class TreeBFS extends AbstractTreeAlogorithm {
public static void main(String[] args){
printAsBinaryTree();
System.out.print("BFS : ");
bfs();
}
private static void bfs(){
Queue<Integer> queue = new LinkedList<>();
queue.add(0);
while(!queue.isEmpty()){
int parent = queue.poll();
System.out.print(parent+" -> ");
int left = parent*2+1;
int right = parent*2+2;
if(left>=field.length) continue;
else if(right>=field.length) queue.add(left);
else{
queue.add(left);
queue.add(right);
}
}
}
}