Study hard

(c++)백준 1991번: 트리 순회 본문

백준/bfs, dfs

(c++)백준 1991번: 트리 순회

Nimgnoej 2020. 6. 22. 16:59

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

 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자

www.acmicpc.net

[풀이]

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;
}