출처 : https://www.acmicpc.net/problem/1991
node 클래스를 만들어서 left 자식과 right 자식을 관리해주면 된다. 쉬운 문제였다 !
package com.ll.boj.silver.p1991;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
public class Main {
static class node {
int left;
int right;
public node(int left, int right) {
this.left = left;
this.right = right;
}
}
static List<node>[] graph;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
sc.nextLine();
graph = new List[n];
for(int i=0; i<n; i++) graph[i] = new ArrayList<>();
for(int i=0; i<n; i++) {
String[] tmp = sc.nextLine().split(" ");
int root = tmp[0].charAt(0) - 'A';
int left = tmp[1].charAt(0) - 'A';
int right = tmp[2].charAt(0) - 'A';
graph[root].add(new node(left, right));
}
preorder(0);
System.out.println();
inorder(0);
System.out.println();
postorder(0);
}
private static void postorder(int start) {
for(node x : graph[start]) {
if (x.left != -19) postorder(x.left);
if (x.right != -19) postorder(x.right);
System.out.print((char)(start + 'A'));
}
}
private static void inorder(int start) {
for(node x : graph[start]) {
if (x.left != -19) inorder(x.left);
System.out.print((char)(start + 'A'));
if (x.right != -19) inorder(x.right);
}
}
private static void preorder(int start) {
for(node x : graph[start]) {
System.out.print((char)(start + 'A'));
if (x.left != -19) preorder(x.left);
if (x.right != -19) preorder(x.right);
}
}
}