https://www.acmicpc.net/problem/4661
4661번: Falling Leaves
For each input data set, there is a unique binary search tree that would produce the sequence of leaves. The output is a line containing only the preorder traversal of that tree, with no blanks.
www.acmicpc.net
사실 동국대학교 자료구조 시간에 과제로 풀었던 문제인데 2000 mid icpc 문제라 백준에도 있더라구요 ㅋㅋ
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
|
#include <iostream>
#include <string>
using namespace std;
string preorder(int level, string leaves[]);
int main(void) {
string input_line;
do {
string* leaves = new string[26];
int level = 0;
getline(std::cin, input_line);
while (input_line[0] != '$' && input_line[0] != '*') {
leaves[level] = input_line;
level++;
getline(std::cin, input_line);
}
cout << preorder(level, leaves) << "\n";
} while (input_line[0] == '*');
}
string preorder(int level, string leaves[]) {
while (level > 0 && leaves[level - 1].length() == 0) {
level--;
}
if (level == 0) {
return "";
}
level--;
char root = leaves[level][0];
string* left = new string[level];
string* right = new string[level];
for (int i = 0; i < level; i++) {
int past = 0;
while ((past < int(leaves[i].length())) && (leaves[i][past] < root)) {
past++;
}
left[i] = leaves[i].substr(0, past);
right[i] = leaves[i].substr(past);
}
return (root + preorder(level, left) + preorder(level, right));
}
|
cs |
'Problem Solving > 백준' 카테고리의 다른 글
[21099] Four XOR (0) | 2021.09.11 |
---|---|
[10943] 랜덤 게임~ (0) | 2021.09.04 |
[2108] 통계학 (0) | 2021.08.02 |
[1436] 영화감독 숌 (0) | 2021.07.31 |
[1764] 듣보잡 (0) | 2021.07.29 |