Problem Solving
[백준/1991] 트리 순회 (재귀, 트리)
개발자 쿠키
2025. 10. 14. 23:15
https://www.acmicpc.net/problem/1991
#include <bits/stdc++.h>
using namespace std;
pair<char, char> node[26];
int n;
void preorder(char cur) {
if(cur=='.') return;
cout << cur;
preorder(node[cur-'A'].first);
preorder(node[cur-'A'].second);
}
void inorder(char cur) {
if(cur == '.') return ;
inorder(node[cur-'A'].first);
cout << cur;
inorder(node[cur-'A'].second);
}
void postorder(char cur) {
if(cur == '.') return;
postorder(node[cur-'A'].first);
postorder(node[cur-'A'].second);
cout << cur;
}
int main() {
cin >> n;
for(int i=0; i<n; i++) {
char parent, left, right;
cin >> parent >> left >> right;
node[parent-'A'].first = left;
node[parent-'A'].second = right;
}
preorder('A');
cout << "\n";
inorder('A');
cout << "\n";
postorder('A');
}
node 라는 pair형 배열에 first는 왼쪽자식, second는 오른쪽 자식을 담음
전위 순회 : 현재 노드 출력 -> 왼쪽 자식 출력 -> 오른쪽 자식 출력
중위 순회 : 왼쪽 자식 출력 -> 현재 노드 출력 -> 오른쪽 자식 출력
후위 순회 : 왼쪽 자식 출력 -> 오른쪽 자식 출력 -> 현재 노드 출력