hwooo
BOJ (C/C++) 1991번: 트리 순회 본문
https://www.acmicpc.net/problem/1991


1991번: 트리 순회
첫째 줄에는 이진 트리의 노드의 개수 N(1 ≤ N ≤ 26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 알파
www.acmicpc.net


풀이
노드가 순서대로 주어지는 게 아니라서 벡터로 연결 리스트 생성, 해당 알파벳에 자식 노드를 저장함.부모-자식 관계는 1개씩만 입력되므로 자식은 모두 V[][0] 배열에서 찾고, 저장된 값이 알파벳일 때만 탐색.코드
#include <stdio.h>
#include <iostream>
#include <vector>
#include <ctype.h>
using namespace std;
vector <pair<char, char>> V[26];
void Preorder(int root) {
char l = V[root][0].first, r = V[root][0].second;
printf("%c", root + 'A');
if (isalpha(l)) Preorder(l - 'A');
if (isalpha(r)) Preorder(r - 'A');
}
void Inorder(int root) {
char l = V[root][0].first, r = V[root][0].second;
if (isalpha(l)) Inorder(l - 'A');
printf("%c", root + 'A');
if (isalpha(r)) Inorder(r - 'A');
}
void Postorder(int root) {
char l = V[root][0].first, r = V[root][0].second;
if (isalpha(l)) Postorder(l - 'A');
if (isalpha(r)) Postorder(r - 'A');
printf("%c", root + 'A');
}
int main() {
int n;
char s[7];
scanf("%d\n", &n);
for (int i = 0; i < n; i++) {
cin.getline(s, 7);
V[s[0] - 'A'].push_back({ s[2], s[4] });
}
Preorder(0); printf("\n");
Inorder(0); printf("\n");
Postorder(0); printf("\n");
return 0;
}
'Study > Algorithm' 카테고리의 다른 글
| BOJ (C/C++) 2028번: 자기복제수 (0) | 2022.11.25 |
|---|---|
| BOJ (C/C++) 14494번: 다이나믹이 뭐예요? (0) | 2022.11.25 |
| BOJ (C/C++) 10953번: A+B - 6 (0) | 2022.11.24 |
| BOJ (C/C++) 10817번: 세 수 (0) | 2022.11.24 |
| BOJ (C/C++) 11478번: 서로 다른 부분 문자열의 개수 (0) | 2022.11.23 |