본문 바로가기

알고리즘/트리

[B1991] - 트리 순회

https://www.acmicpc.net/problem/1991

postorder inorder preorder에 따라 출력하면 된다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
#include <iostream>
#include <vector>
using namespace std;
struct tree {
    int left;
    int right;
};
tree a[52];
void postorder(int x) {
    if (x == -1)
        return;
    postorder(a[x].left);
    postorder(a[x].right);
    cout << (char)(x + 'A');
}
void inorder(int x) {
    if (x == -1)
        return;
    inorder(a[x].left);
    cout << (char)(x + 'A');
    inorder(a[x].right);
}
void preorder(int x) {
    if (x == -1)
        return;
    cout << (char)(x + 'A');
    preorder(a[x].left);
    preorder(a[x].right);
}
int main()
{
    int n;
    cin >> n;
    for (int i = 0; i < n; i++) {
        char node, left, right;
        cin >> node >> left >> right;
        int x = node - 'A';
        if(left=='.')
            a[x].left = -1;
        else
            a[x].left = left - 'A';
        if (right == '.')
            a[x].right = -1;
        else
            a[x].right = right - 'A';
    }
    preorder(0); cout << '\n';
    inorder(0); cout << '\n';
    postorder(0); cout << '\n';
}
cs