문제
Code
package test;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.util.StringTokenizer;
public class P1991 {
static class Node {
char name;
Node left;
Node right;
Node(char name, Node left, Node right) {
this.name = name;
this.left = left;
this.right = right;
}
}
static Node head = new Node('A', null, null);
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringTokenizer st;
int N = Integer.parseInt(br.readLine());
for(int i = 0; i < N; i++) {
st = new StringTokenizer(br.readLine(), " ");
char root = st.nextToken().charAt(0);
char left = st.nextToken().charAt(0);
char right = st.nextToken().charAt(0);
insertNode(head, root, left, right);
}
preOrder(head);
System.out.println();
inOrder(head);
System.out.println();
postOrder(head);
}
private static void insertNode(Node temp, char root, char left, char right) {
if(temp.name == root) {
temp.left = (left == '.' ? null : new Node(left, null, null));
temp.right = (right == '.' ? null : new Node(right, null, null));
} else {
if(temp.left != null) {
insertNode(temp.left, root, left, right);
}
if(temp.right != null) {
insertNode(temp.right, root, left, right);
}
}
}
private static void preOrder(Node node) {
if(node == null) {
return;
}
System.out.print(node.name);
preOrder(node.left);
preOrder(node.right);
}
private static void inOrder(Node node) {
if(node == null) {
return;
}
inOrder(node.left);
System.out.print(node.name);
inOrder(node.right);
}
private static void postOrder(Node node) {
if(node == null) {
return;
}
postOrder(node.left);
postOrder(node.right);
System.out.print(node.name);
}
}
참고 : https://velog.io/@gandi0330/Java-%EB%B0%B1%EC%A4%80-%ED%8A%B8%EB%A6%AC-%EC%88%9C%ED%9A%8C-1991%EB%B2%88