https://www.acmicpc.net/problem/1991
- inorder, preorder, postorder 각각 왼루오, 루왼오, 왼오루 로 순회순서를 외운다
- 노드 자료값이 대문자 알파벳이므로 'A'를 빼서 노드벡터의 배열의 인덱스로 치환하면 치환하면 노드를 더 간단하게 구현할 수 있다.
#include <iostream>
#include <vector>
using namespace std;
struct Node {
char left, right;
};
vector<Node> tree[26]; // A~Z
void preorder(char root) {
Node rootNode = tree[root - 'A'].front();
char left = rootNode.left;
char right = rootNode.right;
cout << root;
if (left != '.') preorder(left);
if (right != '.') preorder(right);
}
void inorder(char root) {
Node rootNode = tree[root - 'A'].front();
char left = rootNode.left;
char right = rootNode.right;
if (left != '.') inorder(left);
cout << root;
if (right != '.') inorder(right);
}
void postorder(char root) {
Node rootNode = tree[root - 'A'].front();
char left = rootNode.left;
char right = rootNode.right;
if (left != '.') postorder(left);
if (right != '.') postorder(right);
cout << root;
}
int main() {
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
cout.tie(nullptr);
int n;
cin >> n;
for (int i = 0; i < n; ++i) {
char root, left, right;
cin >> root >> left >> right;
tree[root - 'A'].push_back({left, right});
}
preorder('A');
cout << '\n';
inorder('A');
cout << '\n';
postorder('A');
return 0;
}
// inorder : 왼루오
// preorder : 루왼오
// postorder : 왼오루
'Algorithm > BOJ' 카테고리의 다른 글
BOJ 17281 - ⚾ 야구(순열, 백트래킹, 브루트포스, 구현) (0) | 2021.08.03 |
---|---|
BOJ 2263 - 트리의 순회(tree) (0) | 2021.07.20 |
boj 21610 - 마법사 상어와 비바라기(구현, 좌표문제) (0) | 2021.07.17 |
boj 19237 - 어른 상어(구현) (0) | 2021.07.08 |
boj 17140 - 이차원배열과 연산(구현, 정렬) (0) | 2021.07.08 |