1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net
'인덱스를 알파벳으로 해야겠구나'라고 생각해버려서 map을 썼다.
근데 다른 사람들 풀이를 보니 이차원배열 혹은 pair의 배열을 만들고 인덱스를
(대문자 알파벳 - 'A')로 써서 해결했던데 이걸 왜 생각을 못했나 싶다.
#include <iostream>
#include <map>
std::map<char, std::pair<char, char>> edges;
std::string pre_str = "";
std::string in_str = "";
std::string post_str = "";
void traversal(char node) {
pre_str += node;
if (edges[node].first != '.') {
traversal(edges[node].first);
}
in_str += node;
if (edges[node].second != '.') {
traversal(edges[node].second);
}
post_str += node;
}
int main() {
int n = 0;
std::cin >> n;
for (int i = 0; i < n; i++) {
char parent, left, right;
std::cin >> parent >> left >> right;
edges.insert({parent, {left, right}});
}
traversal('A');
std::cout << pre_str << "\n" << in_str << "\n" << post_str << "\n";
return 0;
}
'PS > BOJ' 카테고리의 다른 글
BOJ 2638: 치즈 [C++] (0) | 2022.12.01 |
---|---|
BOJ 2096: 내려가기 [C++] (0) | 2022.11.25 |
BOJ 1967 : 트리의 지름 [C++] (0) | 2022.11.23 |
BOJ 1916 : 최소비용 구하기 [C++] (0) | 2022.11.18 |
BOJ 1865 : 웜홀 [C++] (0) | 2022.11.11 |