[백준] 1991 트리 순회

0

백준

목록 보기
184/271
post-thumbnail
post-custom-banner

[백준] 1991 트리 순회

#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int n;
vector<vector<int>> adj(26, vector<int>());

void preorder(int cur) {
	cout << (char)(cur + 'A');
	if (adj[cur][0] != -1) preorder(adj[cur][0]); 
	if (adj[cur][1] != -1) preorder(adj[cur][1]);
}

void inorder(int cur) {
	if (adj[cur][0] != -1) inorder(adj[cur][0]);
	cout << (char)(cur + 'A');
	if (adj[cur][1] != -1) inorder(adj[cur][1]);
}

void postorder(int cur) {
	if (adj[cur][0] != -1) postorder(adj[cur][0]);
	if (adj[cur][1] != -1) postorder(adj[cur][1]);
	cout << (char)(cur + 'A');
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	
	cin >> n;
	for (int i = 0; i < n; ++i) {
		char parent, child1, child2;
		cin >> parent >> child1 >> child2;

		//왼쪽 자식
		if (child1 != '.') adj[parent - 'A'].push_back(child1 - 'A');
		if (child1 == '.') adj[parent - 'A'].push_back(-1);
		
		//오른쪽 자식
		if (child2 != '.') adj[parent - 'A'].push_back(child2 - 'A');
		if (child2 == '.') adj[parent - 'A'].push_back(-1);
	}
	
	preorder(0);
	cout << "\n";
	inorder(0);
	cout << "\n";
	postorder(0);
	return 0;
}
#include <vector>
#include <algorithm>
#include <iostream>
using namespace std;

int n;
vector<vector<char>> adj(26, vector<char>());

void preorder(int cur) {
	cout << (char)(cur + 'A');
	if (adj[cur][0] != '.') preorder(adj[cur][0] - 'A'); 
	if (adj[cur][1] != '.') preorder(adj[cur][1] - 'A');
}

void inorder(int cur) {
	if (adj[cur][0] != '.') inorder(adj[cur][0] - 'A');
	cout << (char)(cur + 'A');
	if (adj[cur][1] != '.') inorder(adj[cur][1] - 'A');
}

void postorder(int cur) {
	if (adj[cur][0] != '.') postorder(adj[cur][0] - 'A');
	if (adj[cur][1] != '.') postorder(adj[cur][1] - 'A');
	cout << (char)(cur + 'A');
}

int main() {
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	
	cin >> n;
	for (int i = 0; i < n; ++i) {
		char parent, child1, child2;
		cin >> parent >> child1 >> child2;
		
		//왼쪽 자식
		adj[parent - 'A'].push_back(child1);
		//오른쪽 자식
		adj[parent - 'A'].push_back(child2);
	}
	
	preorder(0);
	cout << "\n";
	inorder(0);
	cout << "\n";
	postorder(0);
	return 0;
}
profile
Be able to be vulnerable, in search of truth
post-custom-banner

0개의 댓글