Problem
Problem URL : 트리 순회
[1] Answer Code (17. 12. 21)
#include<iostream>
#include<vector>
using namespace std;
vector<pair<char, char>> v[30];
void preOrder(char root){
char l = v[root-'A'].front().first;
char r = v[root-'A'].front().second;
printf("%c",root);
if( l != '.')
preOrder(l);
if( r != '.')
preOrder(r);
}
void inOrder(char root){
char l = v[root-'A'].front().first;
char r = v[root-'A'].front().second;
if( l != '.')
inOrder(l);
printf("%c",root);
if( r != '.')
inOrder(r);
}
void postOrder(char root){
char l = v[root-'A'].front().first;
char r = v[root-'A'].front().second;
if( l != '.')
postOrder(l);
if( r != '.')
postOrder(r);
printf("%c",root);
}
int main(){
int n;
cin >> n;
for(int i=0; i<n; i++){
char m,l,r;
scanf(" %c %c %c",&m,&l,&r);
v[m-'A'].push_back(make_pair(l, r));
}
preOrder('A'); cout<< endl;
inOrder('A'); cout<< endl;
postOrder('A'); cout<< endl;
return 0;
}
[2] Answer Code (18. 09. 13)
#include<iostream>
using namespace std;
int tree[30][3];
void preOrder(int idx){
printf("%c",tree[idx][0]+65);
if( tree[idx][1] != -1)
preOrder(tree[idx][1]);
if( tree[idx][2] != -1)
preOrder(tree[idx][2]);
}
void inOrder(int idx){
if( tree[idx][1] != -1)
inOrder(tree[idx][1]);
printf("%c",tree[idx][0]+65);
if( tree[idx][2] != -1)
inOrder(tree[idx][2]);
}
void postOrder(int idx){
if( tree[idx][1] != -1)
postOrder(tree[idx][1]);
if( tree[idx][2] != -1)
postOrder(tree[idx][2]);
printf("%c",tree[idx][0]+65);
}
int main(){
int n;
cin >> n;
while (n--) {
char a,b,c;
scanf(" %c %c %c",&a, &b, &c);
tree[ a-65 ][0] = a - 65;
b != '.' ? tree[ a-65 ][1] = b - 65 : tree[ a-65 ][1] =-1;
c != '.' ? tree[ a-65 ][2] = c - 65 : tree[ a-65 ][2] = -1;
}
preOrder(0);
cout << endl;
inOrder(0);
cout << endl;
postOrder(0);
return 0;
}
Review
-
SK Hynix 코테 준비할겸 다시 풀어봤다.
-
코테에서는 STL사용이 불가하기에 Vector를 사용하지 않고 배열로 풀었다.
-
관련된 Key Point도 있으니 한번 보는것을 추천 !