1. 문제
위 그림과 같은 이진트리를 레벨 탐색 연습하시오.
레벨 탐색 순회 출력: 1 2 3 4 5 6 7
2. 나의 풀이
강의 보고 진행
3 - 1. 강의 풀이
트리 선언 후
0, 1, 2 레벨의 트리들을 순회한다.
Q에 root 를 넣는다. (순회)
root를 Q에서 빼고 root.lt와 rt를 Q에 넣는다.
이를 반복한다.
3 - 2. 강의 코드
package BFS_DFS;
import java.util.*;
class Node{
int data;
Node lt;
Node rt;
Node(int value) {
this.data = value;
}
}
public class bfs07 {
static Node root;
public static void BFS(Node root) { //bfs로 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++) { //트리 수 만큼 q.poll하고 양 옆 트리를 Q에 다시 넣는다.
Node next = q.poll();
System.out.print(next.data +" ");
if(next.lt!=null) q.offer(next.lt);
if(next.rt!=null) q.offer(next.rt);
}
L++;
System.out.println();
}
}
public static void main(String[] args) {
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);
root.rt.lt = new Node(6);
root.rt.rt = new Node(7);
BFS(root);
}
}
4. 얻어갈 점
코드 읽으면 문제될 게 없음
'자바 알고리즘 문제풀이 > Recursive, Tree, Graph(DFS, BFS 기초)' 카테고리의 다른 글
★9. 말단 노드까지 최소 간선 DFS (0) | 2023.11.22 |
---|---|
8. 송아지 찾기 1 (BFS: 상태 트리 검색) (1) | 2023.11.20 |
6. 부분 집합 구하기(DFS) (0) | 2023.11.16 |
5. 이진트리순회(DFS: Depth - First - Searching) (1) | 2023.11.15 |
4. 피보나치 재귀(메모이제이션) (0) | 2023.11.14 |