본문 바로가기
Algorithm/BOJ

BOJ 1991 - 트리 순회(tree)

by Ellery 2021. 7. 19.

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

 

1991번: 트리 순회

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

www.acmicpc.net

- 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 : 왼오루