class Node{
int data;
Node lt,rt;
public Node(int val){
data = val;
lt = rt = null;
}
}
public class Main{
Node root;
public void BFS(Node root){
...
}
public static void main(String[] args){
Main tree = new Main();
tree.root = new Node(1);
tree.root.lt = new Node(2);
tree.root.rt = new Node(3);
tree.root.lt.lt = new Node(4);
tree.root.lt.rt = new Node(5);
tree.root.rt.lt = new Node(6);
tree.root.rt.rt = new Node(7);
tree.BFS(tree.root);
}
}
Node형식의 객체를 생성하고,
main메소드에서 Main객체인 tree를 사용해
각각의 노드 data를 저장해준다.
public void BFS(Node root){
Queue<Node> Q = new LinkedList<>();
Q.offer(root);
int L = 0;
while(!Q.isEmpty()){
int len = Q.size();
System.out.print(L + " : ");
for(int i=0;i<len;i++){
Node cur = Q.poll();
System.out.print(cur.data+" ");
if(cur.lt != null)
Q.offer(cur.lt);
if(cur.rt != null)
Q.offer(cur.rt);
}
L++;
System.out.println();
}
}
package Nodes.bfs_breath_first_search;
import java.util.LinkedList;
import java.util.Queue;
class Node{
int data;
Node lt,rt;
public Node(int val){
data = val;
lt = rt = null;
}
}
public class Main {
Node root;
public void BFS(Node root){
Queue<Node> Q = new LinkedList<>();
//Q.add(root);
Q.offer(root);
int L = 0;
// 비어있지 않을때 while문이 동작해야 하므로
while(!Q.isEmpty()){
int len = Q.size();
System.out.print(L+" : ");
for(int i=0;i<len;i++){
Node cur = Q.poll();
System.out.print(cur.data+ " ");
if(cur.lt != null)
Q.offer(cur.lt);
if(cur.rt != null)
Q.offer(cur.rt);
}
L++;
System.out.println();
}
}
public static void main(String[] args) {
Main tree = new Main();
tree.root = new Node(1);
tree.root.lt = new Node(2);
tree.root.rt = new Node(3);
tree.root.lt.lt = new Node(4);
tree.root.lt.rt = new Node(5);
tree.root.rt.lt = new Node(6);
tree.root.rt.rt = new Node(7);
tree.BFS(tree.root);
}
}