본문 바로가기
🥇Baekjoon Solutions/자료구조

[C++] 백준 1991번: 트리 순회

by 코푸는 개발자 2021. 7. 23.
728x90

 

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

 

1991번: 트리 순회

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

www.acmicpc.net

 

최초 무식한 풀이

- 각각의 함수들을 개별적으로 만들어 풀이 진행

- 트리구조를 간단한 구조체를 활용하여 구현(노드가 최대 26개 만들어진다는 것에 착안하여 간단한 구조 구현)

#include <iostream>
#include <vector>

using namespace std;

struct tree
{
	char left;
	char right;
};

vector<tree>T(26);

//재귀 함수를 통한 트리 출력

void solve1(char root) {//전위 순회
	cout << root;
	if (T[root - 'A'].left == '.');
	else
		solve1(T[root - 'A'].left);
	if (T[root - 'A'].right == '.');
	else
		solve1(T[root - 'A'].right);
}

void solve2(char root) {//중위 순회
	if (T[root - 'A'].left == '.');
	else
		solve2(T[root - 'A'].left);
	cout << root;
	if (T[root - 'A'].right == '.');
	else
		solve2(T[root - 'A'].right);
}

void solve3(char root) {//후위 순회
	if (T[root - 'A'].left == '.');
	else
		solve3(T[root - 'A'].left);
	if (T[root - 'A'].right == '.');
	else
		solve3(T[root - 'A'].right);
	cout << root;
}

int main() {
	int N;
	char root, L, R;
	cin >> N;
	
	for (int i = 0; i < N; i++) {
		cin >> root >> L >> R;
		T[root - 'A'] = { L,R };
	}
	
	solve1('A');
	cout << endl;
	solve2('A');
	cout << endl;
	solve3('A');

	return 0;
}
728x90

'🥇Baekjoon Solutions > 자료구조' 카테고리의 다른 글

[C++] 백준 17298번: 오큰수  (0) 2021.07.28

댓글