트리 순회 문제입니다.
전위 순회, 중위 순회, 후위 순회에 대한 결과값을 출력해주면 됩니다.
전위 : 루트 - 왼쪽 - 오른쪽
중위 : 왼쪽 - 루트 - 오른쪽
후위 : 왼쪽 - 오른쪽 - 루트
위 순서대로 재귀함수를 실행해주면 됩니다.
import java.io.*;
import java.util.*;
public class Main {
static BufferedReader br;
static BufferedWriter bw;
static int[][] arr;
static int n;
public static void main(String[] args) throws Exception {
br = new BufferedReader(new InputStreamReader(System.in));
bw = new BufferedWriter(new OutputStreamWriter(System.out));
n = Integer.parseInt(br.readLine());
arr = new int[27][2];
for (int i = 0; i < n; ++i) {
String str = br.readLine();
int a = str.charAt(0) - 'A';
int b = str.charAt(2) - 'A';
int c = str.charAt(4) - 'A';
if (b == -19) {
b = 26;
}
if (c == -19) {
c = 26;
}
arr[a][0] = b;
arr[a][1] = c;
}
preorder(0);
bw.write("\n");
inorder(0);
bw.write("\n");
postorder(0);
bw.write("\n");
bw.close();
}
public static void preorder(int index) throws Exception {
bw.write(index + 'A');
if (arr[index][0] != 26) {
preorder(arr[index][0]);
}
if (arr[index][1] != 26) {
preorder(arr[index][1]);
}
}
public static void inorder(int index) throws Exception {
if (arr[index][0] != 26) {
inorder(arr[index][0]);
}
bw.write(index + 'A');
if (arr[index][1] != 26) {
inorder(arr[index][1]);
}
}
public static void postorder(int index) throws Exception {
if (arr[index][0] != 26) {
postorder(arr[index][0]);
}
if (arr[index][1] != 26) {
postorder(arr[index][1]);
}
bw.write(index + 'A');
}
}
'알고리즘' 카테고리의 다른 글
[Java] 백준 16194번 카드 구매하기 2 (0) | 2023.07.22 |
---|---|
[Java] 백준 10819번 차이를 최대로 (0) | 2023.07.22 |
[Java] 백준 3343번 장미 (0) | 2023.07.22 |
[Java] 백준 2141번 우체국 (0) | 2023.07.19 |
[Java] 백준 24956번 나는 정말 휘파람을 못 불어 (1) | 2023.07.18 |