728x90
반응형
아래 그림과 같은 이진트리를 레벨탐색 연습하시요.
레벨 탐색 순회 출력 : 1 2 3 4 5 6 7
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<Node>();
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();
}
}
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);
}
}
728x90
반응형
'코딩 테스트 > 7. Recursive, Tree, Graph' 카테고리의 다른 글
Q7 - 10 Tree 말단 노드까지의 가장 짧은 경로(BFS) (0) | 2021.11.14 |
---|---|
Q7 - 9 Tree 말단노드까지의 가장 짧은 경로(DFS) (0) | 2021.11.14 |
Q7 - 6 부분집합 구하기(DFS) (0) | 2021.11.08 |
Q7 - 8 송아지 찾기(BFS : 상태트리탐색) (0) | 2021.11.08 |
Q7 - 5 이진트리 순회(깊이 우선 탐색 (0) | 2021.11.08 |