인프런 커뮤니티 질문&답변
안녕하세요 !
작성
·
220
0
안녕하세요. 강의 잘 보고 있어요 !
문제에는 재귀를 왼쪽 오른쪽 자식 노드 각각 호출하는데..
이렇게 이진트리순회 문제를 풀어도 되는건지 궁금합니다!
감사합니다.
import java.util.ArrayList;
public class Test {
public static boolean[] visited = new boolean[8]; // node + 1
public static ArrayList<ArrayList<Integer>> graph = new ArrayList<>();
public void DFS(int x){
if (!visited[x]){
visited[x] = true;
System.out.print(x + " ");
for (int i=0; i<graph.get(x).size(); i++){
Integer y = graph.get(x).get(i);
if (!visited[y]){
DFS(y);
}
}
}
}
public static void main(String[] args) {
Test test = new Test();
for (int i=0; i<visited.length; i++){
graph.add(new ArrayList<>());
}
graph.get(1).add(2);
graph.get(1).add(3);
graph.get(2).add(4);
graph.get(2).add(5);
graph.get(3).add(6);
graph.get(3).add(7);
graph.get(4).add(2);
graph.get(5).add(2);
graph.get(6).add(3);
graph.get(7).add(3);
test.DFS(1);
}
}





