Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 백준 패션왕 신해빈
- 백준 14246번 K보다 큰 구간
- 백준 dfs
- 백준 1049번
- 백준 1049번 기타줄
- C# 병합정렬
- C++ 9996
- 백준 10709
- 고정 소수점
- 백준 2309번 일곱 난쟁이
- 백준 9375번 패션왕 신해빈
- 상월곡역 학원
- 월곡중학교 학원추천
- OS
- 월곡중 학원
- 백준 K보다 큰 구간
- C++ 문자열
- 월곡동 학원추천
- c++ split
- 백준 한국이 그리울 땐 서버에 접속하지
- 월곡역 학원
- 운영체제
- 상월곡동 학원
- 백준 14246번
- 성북구 학원
- c++ 조합
- DFS
- 서울사대부고 학원
- 관리형 학원
- 백준 토마토
Archives
- Today
- Total
키베이루's diary
[C++] 백준 1991번 트리 순회 본문
1) 문제설명
https://www.acmicpc.net/problem/1991
1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net
2) 아이디어
트리를 구조체가 아닌 2차 배열로 구현하였다.
nodes [][0] : 왼쪽 자식, nodes [][1] : 오른쪽 자식으로 설정한다.
왼쪽 입력이. 일 경우 -1을 할당, 마찬가지로 오른쪽 입력이. 일 경우 -1을 할당하고 나머지를 자식들로 할당한다.
이후 순서대로 전위, 중위, 후위 순회 순으로 출력한다.
3) 코드
#include<iostream>
#include<queue>
#include<deque>
#include<string.h>
#include<math.h>
#include<cmath>
#include<stack>
#include<algorithm>
using namespace std;
int n;
char nodes[27][2]; // nodes[][0] : 왼쪽자식 nodes[][1] : 오른쪽자식
void preorder(int a) {
if (a == -1) {
return;
}
printf("%c", a + 'A');
preorder(nodes[a][0]);
preorder(nodes[a][1]);
}
void inorder(int a) {
if (a == -1) {
return;
}
inorder(nodes[a][0]);
printf("%c", a + 'A');
inorder(nodes[a][1]);
}
void postorder(int a) {
if (a == -1) {
return;
}
postorder(nodes[a][0]);
postorder(nodes[a][1]);
printf("%c", a + 'A');
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
char C, L, R;
cin >> C >> L >> R;
if (L == '.') { // 왼쪽자식이 .일 경우 왼쪽자식에게 -1 할당
nodes[C - 'A'][0] = -1;
}
else { // 왼쪽자식이 .이 아닐 경우
nodes[C - 'A'][0] = L - 'A';
}
if (R == '.') {
nodes[C - 'A'][1] = -1;
}
else {
nodes[C - 'A'][1] = R - 'A';
}
}
preorder(0);
cout << endl;
inorder(0);
cout << endl;
postorder(0);
}
Comments