Study hard
(c++)백준 1991번: 트리 순회 본문
https://www.acmicpc.net/problem/1991
[풀이]
Tree[][2]배열에 각 노드의 왼쪽 자식 노드 번호와 오른쪽 자식 노드 번호를 저장하였다.
#include <iostream>
using namespace std;
int N;
char Tree[27][2];//[x][0]:x의 왼쪽 자식, [x][1]:x의 오른쪽 자식
void input() {
cin >> N;
for (int i = 0; i < N; i++) {
char a, b, c;
cin >> a >> b >> c;
Tree[a - 'A'][0] = b;
Tree[a - 'A'][1] = c;
}
}
void preorder(int node) {
if (node + 'A' == '.')
return;
cout << char(node + 'A');
preorder(Tree[node][0] - 'A');
preorder(Tree[node][1] - 'A');
return;
}
void inorder(int node) {
if (node + 'A' == '.')
return;
inorder(Tree[node][0] - 'A');
cout << char(node + 'A');
inorder(Tree[node][1] - 'A');
return;
}
void postorder(int node) {
if (node + 'A' == '.')
return;
postorder(Tree[node][0] - 'A');
postorder(Tree[node][1] - 'A');
cout << char(node + 'A');
return;
}
void solution() {
input();
//전위순회
preorder(0);
cout << endl;
//중위순회
inorder(0);
cout << endl;
//후위순회
postorder(0);
cout << endl;
}
int main() {
solution();
return 0;
}
'백준 > bfs, dfs' 카테고리의 다른 글
(c++)백준 1967번: 트리의 지름 (0) | 2020.06.23 |
---|---|
(c++)백준 11725번: 트리의 부모 찾기 (0) | 2020.06.22 |
(c++)백준 2178번: 미로 탐색 (0) | 2020.06.20 |
(c++)백준 7576번: 토마토 (0) | 2020.06.20 |
(c++)백준 4964번: 섬의 개수 (0) | 2020.06.20 |