[BOJ] 5639번 이진 검색 트리 - C++

"트리"

Posted by Yongmin on August 19, 2021

문제

이진 검색 트리

풀이

preorder가 주어졌을 때, postorder를 구하는 코드이다. while(scanf("%d", &input) != -1)를 통해 입력의 갯수, 입력의 마지막 제한이 없는 입력을 받았다. preorder의 root는 맨 앞에 위치해있으며, root보다 큰 수가 나오기 직전 까지 왼쪽 루트에 해당하고 그 이후부터 오른쪽 루트에 해당한다. 이를 토대로, root보다 큰 index를 확인하여, 분할정복을 실행한다. postorder를 출력하는 문제이므로, 해당 root에서 왼쪽 루트, 오른쪽 루트가 모두 끝났을 때 해당 root를 출력하여 정답을 도출한다.

소스 코드

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
#include <iostream>
#include <vector>
#include <string.h>

#define INF 987654321

using namespace std;

vector<int> preorder_vector;

void postorder(int start, int end){
    
    
    if(start > end) return;
    
    int root = preorder_vector[start];
    
    int index = start;
    while(root >= preorder_vector[index]){
        
        index++;
        
        if(index > end){
            index = end + 1;
            break;
        }
    }
    
    
    
    postorder(start+1, index-1);
    postorder(index, end);
    
    printf("%d\n", root);
    
    
}
 
int main(){
    
    int input;
    while(scanf("%d", &input) != -1){
        preorder_vector.push_back(input);
    }
    int N = preorder_vector.size();
    postorder(0, N-1);
    
}


# # #