BFS는 층별로 탐색을 한다. 각 층을 탐색하면서 말단 노드인 것을 확인하면 탐색하던 층을 반환한다. 그래서 DFS보다 최단 거리를 찾는 것에 더 효율적인 것이다.

이전 글에서 설명을 충분히 했다고 여겨서 바로 코드로 구현해볼 것이다.

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
class Node{
    int data;
    Node lt, rt;
 
    public Node(int root){
        data = root;
        lt = rt = null;
    }
}
 
public class Practice {
    public static Node root;
    public static Queue<Node> q;
 
    public static int BFS(){
        int L=0;
        q.offer(root);
        while(!q.isEmpty()){
            int len = q.size();
            for(int i=0; i<len; i++){
                Node cur = q.poll();
                if(cur.lt == null && cur.rt == nullreturn L;
                if(cur.lt != null) q.offer(cur.lt);
                if(cur.rt != null) q.offer(cur.rt);
            }
            L++;
        }
        return -1;
    }
 
    public static void main(String[] args){
        q = new LinkedList<>();
        root = new Node(1);
        root.lt = new Node(2);
        root.rt = new Node(3);
        root.lt.lt = new Node(4);
        root.lt.rt = new Node(5);
 
        q.offer(root);
        System.out.println(BFS());
    }
}
cs

'알고리즘' 카테고리의 다른 글

비트마스크(1)  (0) 2023.03.14
그래프와 인접행렬  (0) 2022.12.11
Tree 말단 노드까지의 가장 짧은 경로(DFS)  (0) 2022.12.11
이진트리 순회(너비우선탐색 : 레벨탐색)  (2) 2022.12.10
부분집합 구하기(DFS)  (0) 2022.12.10