https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자
www.acmicpc.net
기본적인 트리 순회 문제다.
재귀적인 방법으로 전위, 중위, 후위 순회를 구현했다.
#include <iostream>
#include <vector>
using namespace std;
int n;
vector<int> tree[26];
string preorder(int cur) {
string ret = "";
ret.push_back('A' + cur);
if (tree[cur][0] > 0) ret += preorder(tree[cur][0]);
if (tree[cur][1] > 0) ret += preorder(tree[cur][1]);
return ret;
}
string inorder(int cur) {
string ret = "";
if (tree[cur][0] > 0) ret += inorder(tree[cur][0]);
ret.push_back('A' + cur);
if (tree[cur][1] > 0) ret += inorder(tree[cur][1]);
return ret;
}
string postorder(int cur) {
string ret = "";
if (tree[cur][0] > 0) ret += postorder(tree[cur][0]);
if (tree[cur][1] > 0) ret += postorder(tree[cur][1]);
ret.push_back('A' + cur);
return ret;
}
int main() {
ios::sync_with_stdio(0), cin.tie(0), cout.tie(0);
char c1, c2, c3;
cin >> n;
for (int i = 0; i < n; i++) {
cin >> c1 >> c2 >> c3;
if (c2 == '.') c2 = 'A' - 1;
if (c3 == '.') c3 = 'A' - 1;
tree[c1 - 'A'].push_back(c2 - 'A');
tree[c1 - 'A'].push_back(c3 - 'A');
}
cout << preorder(0) << '\n';
cout << inorder(0) << '\n';
cout << postorder(0);
return 0;
}
메모리: 2024 kb | 시간: 0 ms |
'컴퓨터 사이언스 > 1고리즘' 카테고리의 다른 글
백준 2250 : 트리의 높이와 너비 (0) | 2021.07.28 |
---|---|
백준 1240 : 노드사이의 거리 (0) | 2021.07.27 |
백준 1630 : 오민식 (0) | 2021.07.26 |
백준 14442 : 벽 부수고 이동하기 2 (0) | 2021.07.25 |
백준 1300 : K번째 수 (0) | 2021.07.25 |