접근
노드의 값이 A~Z 26개이고, n에 따라 A부터 차례대로 매겨진다는 점에서 Node[n]을 선언하고 -'A' 인덱스로 접근해도 됐었을 것이다. 하지만 map을 사용하면 이런 조건이 없을 때에도 적용 가능할 것 같아서 map으로 구현해봤다. 자식이 없는 경우에 그대로 '.'값을 가지도록 만들고 순회를 돌 때 조건을 확인해줘도 되지만, 나는 그냥 null값을 가지도록 했다.
코드
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;
public class BJ1991 {
static class Node{
char val;
Node leftChild, rightChild;
Node(char val){
this.val = val;
this.leftChild = this.rightChild = null;
}
void preorder(StringBuilder sb){
sb.append(this.val);
if(this.leftChild != null)
this.leftChild.preorder(sb);
if(this.rightChild != null)
this.rightChild.preorder(sb);
}
void inorder(StringBuilder sb){
if(this.leftChild != null)
this.leftChild.inorder(sb);
sb.append(this.val);
if(this.rightChild != null)
this.rightChild.inorder(sb);
}
void postorder(StringBuilder sb){
if(this.leftChild != null)
this.leftChild.postorder(sb);
if(this.rightChild != null)
this.rightChild.postorder(sb);
sb.append(this.val);
}
}
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
// 변수 초기값 설정
int n = Integer.parseInt(br.readLine());
Map<Character, Node> tree = new HashMap<>();
char key = 'A';
for (int i = 0; i < n; i++)
tree.put(key, new Node(key++));
// 트리 정보 저장
for (int i = 0; i < n; i++) {
String[] input = br.readLine().split(" ");
char val = input[0].charAt(0);
char left = input[1].charAt(0);
char right = input[2].charAt(0);
if(left != '.')
tree.get(val).leftChild = tree.get(left);
if(right != '.')
tree.get(val).rightChild = tree.get(right);
}
Node root = tree.get('A');
// 전위 순회
root.preorder(sb);
sb.append("\n");
// 중위 순회
root.inorder(sb);
sb.append("\n");
// 후위 순회
root.postorder(sb);
sb.append("\n");
// 결과 출력
System.out.println(sb);
}
}
'Algorithm' 카테고리의 다른 글
[백준] 1647: 도시 분할 계획 JAVA (0) | 2023.02.26 |
---|---|
[백준] 1068: 트리 JAVA (0) | 2023.02.15 |
[백준] 11725: 트리의 부모 찾기 JAVA (0) | 2023.02.15 |
[백준] 6087: 레이저 통신 JAVA (0) | 2023.02.07 |
[백준] 14938: 서강그라운드 JAVA (0) | 2023.02.07 |