Notice
Recent Posts
Recent Comments
Link
«   2026/02   »
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
Archives
Today
Total
관리 메뉴

hwooo

BOJ (C/C++) 1991번: 트리 순회 본문

Study/Algorithm

BOJ (C/C++) 1991번: 트리 순회

hwooo 2022. 11. 25. 02:37

풀이

노드가 순서대로 주어지는 게 아니라서 벡터로 연결 리스트 생성, 해당 알파벳에 자식 노드를 저장함.부모-자식 관계는 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;
}