CS/baekjoon

[백준 1991번] 트리 순회

hanjongho 2021. 1. 31. 03:17

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

 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자

www.acmicpc.net

풀이) 

재귀가 호출되고, 끝나는 시점만 헷갈리지 않으면 쉽게 풀 수 있었던 문제이다.

#include <iostream>
using namespace std;

int A[27][2];
void preorder(int x)
{
    if (x == -1) return;
    cout << (char)(x + 'A');
    preorder(A[x][0]);
    preorder(A[x][1]);
}

void inorder(int x)
{
    if (x == -1) return;
    inorder(A[x][0]);
    cout << (char)(x + 'A');
    inorder(A[x][1]);    
}

void postorder(int x)
{
    if (x == -1) return;
    postorder(A[x][0]);
    postorder(A[x][1]);
    cout << (char)(x + 'A');
}

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

    int n;
    char x, y, z;
    cin >> n;
    
    for (int i = 1; i <= n; i++)
    {
        cin >> x >> y >> z;
        x -= 'A';
        A[x][0] = y != '.' ? y - 'A' : -1;
        A[x][1] = z != '.' ? z - 'A' : -1;
    }
    preorder(0);
    cout << '\n';
    inorder(0);
    cout << '\n';
    postorder(0);
    cout << '\n';
}

 

 

제 코드는 절대 완벽하지 않습니다

더 좋은 풀이방법 혹은 코드에 관한 질문이 있으시면 언제든 댓글주세요!