1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자
www.acmicpc.net
#include <iostream>
using namespace std;
struct Node {
int left;
int right;
};
Node a[50];
void preorder(int x) {
if (x == -1) return;
cout << (char)(x+'A');
preorder(a[x].left);
preorder(a[x].right);
}
void inorder(int x) {
if (x == -1) return;
inorder(a[x].left);
cout << (char)(x+'A');
inorder(a[x].right);
}
void postorder(int x) {
if (x == -1) return;
postorder(a[x].left);
postorder(a[x].right);
cout << (char)(x+'A');
}
int main() {
int n;
cin >> n;
for (int i=1; i<=n; i++) {
char x, y, z;
cin >> x >> y >> z;
x = x-'A';
if (y == '.') {
a[x].left = -1;
} else {
a[x].left = y-'A';
}
if (z == '.') {
a[x].right = -1;
} else {
a[x].right = z-'A';
}
}
preorder(0);
cout << '\n';
inorder(0);
cout << '\n';
postorder(0);
cout << '\n';
return 0;
}
'Problem set' 카테고리의 다른 글
[백준] 11725 트리의 부모 찾기 (0) | 2021.02.20 |
---|---|
[백준] 2250 트리의 높이와 너비 (0) | 2021.02.20 |
[백준] 1261 알고스팟 (0) | 2021.02.20 |
[백준] 13549 숨박꼭질 3 (0) | 2021.02.20 |
[백준] 14226 이모티콘 (0) | 2021.02.20 |