백준 1991 : 트리 순회

혀니앤·2021년 6월 5일
0

C++ 알고리즘

목록 보기
64/118

https://www.acmicpc.net/problem/1991

1. 접근

  • 이진 트리이므로, 각 노드는 0~2개의 하위 노드를 갖는다.
    => 가로가 2인 배열을 만들 수 있다.
  • 시작은 'A'에서부터만 시작한다.
  • 노드는 A부터 대문자 순서대로 받지만, 입력은 순서대로 받지 않는다.
  • 해당 노드를 순회할 때 문자 그대로 출력해주면 된다. => char 배열을 그대로 사용해도 됨
  • 각 순회 방법은, 순회 순서를 수정하기만 하면 됨
  • 배열 안에 들어가는 값은 char 타입이고, 배열의 index 값은 int형이므로 값 변형을 잘 해주어야 함

2. 나의 풀이

#include <iostream>
#include <cstring>
#define MAX 26
using namespace std;

int n;
char graph[MAX][2];

void preorder(char root) { //전위 순회
	cout << root; //바로 노드를 출력

	for (int i = 0; i < 2; i++) {
		char next = graph[root-'A'][i]; //인덱스 char 타입으로 변환
		if (next !='.') //노드가 비어있지 않으면
			preorder(next);
	}
	return;
}

void inorder(char root) { //중위 순회
	char next = graph[root - 'A'][0];
	if (next != '.')
		inorder(next);

	cout << root;

	next = graph[root - 'A'][1];
	if (next != '.')
		inorder(next);
	return;
}

void postorder(char root) { //후위 순회
	for (int i = 0; i < 2; i++) {
		char next = graph[root - 'A'][i];
		if (next != '.')
			postorder(next);
	}
	cout << root;
	
	return;
}

int main() {
	cin >> n;
	for (int i = 0; i < n; i++) {
		char node;
		cin >> node;
		int r=node-'A'; //노드의 영문자 순서 (노드가 순서대로 입력되지 않으므로.)

		for (int j = 0; j < 2; j++) {
			cin >> graph[r][j];
		}
	}

	preorder('A');
	cout << "\n";

	inorder('A');
	cout << "\n";

	postorder('A');
	cout << "\n";
}
profile
일단 시작하기

0개의 댓글