BOJ/C++
[BOJ] 트리순회
IamToday
2019. 8. 9. 11:04
[문제]
https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자 대문자로 매겨지며, 항상 A가 루트 노드가 된다. 자식 노드가 없는 경우에는 .으로 표현된다.
www.acmicpc.net
[풀이]
1991 | 맞았습니다!! | 1988 | 0 | C++14 / 수정 | 1183 | 9초 전 |
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
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
|
#include <iostream>
#include <vector>
using namespace std;
typedef pair<char, char> pp;
vector<pp> nodes[26]; //왼쪽, 오른쪽 노드를 담을 백터 배열
void preOrder(char root)
{
char left = nodes[root - 'A'].front().first;
char right = nodes[root - 'A'].front().second;
cout << root ;
if (left != '.')
preOrder(left);
if (right != '.')
preOrder(right);
}
void inOrder(char root)
{
char left = nodes[root - 'A'].front().first;
char right = nodes[root - 'A'].front().second;
if (left != '.')
inOrder(left);
cout << root ;
if (right != '.')
inOrder(right);
}
void postOrder(char root)
{
char left = nodes[root - 'A'].front().first;
char right = nodes[root - 'A'].front().second;
if (left != '.')
postOrder(left);
if (right != '.')
postOrder(right);
cout << root ;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(0);
int n;
cin >> n;
char data, left, right;
for (int i = 0; i < n; i++)
{
cin >> data >> left >> right;
nodes[data - 'A'].push_back(pp(left, right)); //부모 노드에 자식들을 이어준다.
}
preOrder('A');
cout << '\n';
inOrder('A');
cout << '\n';
postOrder('A');
cout << '\n';
return 0;
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
|