← Back to Blog

[Baekjoon 1991 | C++] Tree Traversal

computer science > algorithm

2026-07-041 min read

#computer-science #algorithm #baekjoon #problem-solving

문제 링크:

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

Tree에서 0번 index는 left child를 1번 index에는 right child로 두고 순회를 진행했다.

#include <iostream>
using namespace std;

int N;
char MAP[27][2];

void preorder(int N) {
    if (N == -1)
        return;

    cout << (char)(N + 'A');
    preorder(MAP[N][0]);
    preorder(MAP[N][1]);
}

void inorder(int N) {
    if (N == -1)
        return;

    inorder(MAP[N][0]);
    cout << (char)(N + 'A');
    inorder(MAP[N][1]);
}

void postorder(int N) {
    if (N == -1)
        return;

    postorder(MAP[N][0]);
    postorder(MAP[N][1]);
    cout << (char)(N + 'A');
}

int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);

    cin >> N;

    char parent, left, right;
    while (N--) {
        cin >> parent >> left >> right;
        int pIdx = parent - 'A';
        // left node
        if (left == '.')
            MAP[pIdx][0] = -1;
        else
            MAP[pIdx][0] = left - 'A';

        // right node
        if (right == '.')
            MAP[pIdx][1] = -1;
        else
            MAP[pIdx][1] = right - 'A';
    }
    preorder(0);
    cout << '\n';
    inorder(0);
    cout << '\n';
    postorder(0);

    return 0;
}