https://www.acmicpc.net/problem/1991
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.StringTokenizer;
public class Main {
static Node rootNode = new Node('A', null, null);
static class Node{
char name;
Node left;
Node right;
public Node(char name, Node left, Node right) {
this.name = name;
this.left = left;
this.right = right;
}
}
static void addNode(Node node, char head, char left, char right) {
if(node.name==head) {
node.left = (left=='.' ? null : new Node(left, null, null));
node.right = (right=='.' ? null : new Node(right, null, null));
}
else {
if(node.left!=null) addNode(node.left, head, left, right);
if(node.right!=null) addNode(node.right, head, left, right);
}
}
static void preOrder(Node node) {
if(node ==null) return;
System.out.print(node.name);
preOrder(node.left);
preOrder(node.right);
}
static void inOrder(Node node) {
if(node ==null) return;
inOrder(node.left);
System.out.print(node.name);
inOrder(node.right);
}
static void postOrder(Node node) {
if(node ==null) return;
postOrder(node.left);
postOrder(node.right);
System.out.print(node.name);
}
public static void main(String[] args) throws IOException{
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int n = Integer.parseInt(br.readLine());
for(int i=0; i<n; i++) {
StringTokenizer stk = new StringTokenizer(br.readLine());
char head = stk.nextToken().charAt(0);
char left = stk.nextToken().charAt(0);
char right = stk.nextToken().charAt(0);
addNode(rootNode, head, left, right);
}
preOrder(rootNode);
System.out.println();
inOrder(rootNode);
System.out.println();
postOrder(rootNode);
}
}
'[Solved] > BOJ' 카테고리의 다른 글
[백준 1927] 최소 힙 (0) | 2023.04.28 |
---|---|
[백준 1464] 뒤집기 3 (0) | 2023.04.26 |
[백준 5430] AC (0) | 2023.04.26 |
[백준 1021] 회전하는 큐 (0) | 2023.03.31 |
[백준 11275] 트리의 부모찾기 (0) | 2023.03.23 |