기본 콘텐츠로 건너뛰기

백준알고리즘 1991번, 트리 사용하기 풀이

그래프와 트리쪽 알고리즘이 약해서 요즘 이 파트를 공부하고있습니다.
2진 트리의 원소를 입력받아 순회 종류별로 출력해주는 문제입니다.
재귀적으로 깔끔하게 푸는 것이 중요하겠죠!



--------------------------------------------------------------------------------------------

#include <stdio.h>
#include <string.h>
#include <vector>


using namespace std;


class BTreeNode {
public:
char elem;
int lindex;
int rindex;
BTreeNode()
{
BTreeNode(0, 0, 0);
}

BTreeNode(char c, int n1, int n2):elem(c),lindex(n1),rindex(n2)
{
}
};

void Preorder(BTreeNode node);

void Inorder(BTreeNode node);

void Postorder(BTreeNode node);

BTreeNode bt[26];

int main(void) {
memset(bt, 0, sizeof bt);
int t;
char c1, c2, c3;

#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif

scanf("%d\n", &t);
for (int i = 0; i < t; i++) {
scanf("%c %c %c\n", &c1, &c2, &c3);
bt[c1-'A'].elem = c1; bt[c1 - 'A'].lindex = c2 - 'A'; bt[c1 - 'A'].rindex = c3 - 'A';
if (c2 == '.')
bt[c1 - 'A'].lindex = -1;
if (c3 == '.')
bt[c1 - 'A'].rindex = -1;
}

Preorder(bt[0]);
puts("");
Inorder(bt[0]);
puts("");
Postorder(bt[0]);
#ifndef ONLINE_JUDGE
fclose(stdin);
fclose(stdout);
#endif

return 0;
}

void Preorder(BTreeNode node) {
printf("%c", node.elem); 
if (node.lindex != -1)
Preorder(bt[node.lindex]);
if (node.rindex != -1)
Preorder(bt[node.rindex]);
}

void Inorder(BTreeNode node) {
if (node.lindex != -1)
Inorder(bt[node.lindex]);
printf("%c", node.elem);
if (node.rindex != -1)
Inorder(bt[node.rindex]);
}

void Postorder(BTreeNode node) {
if (node.lindex != -1)
Postorder(bt[node.lindex]);
if (node.rindex != -1)
Postorder(bt[node.rindex]);
printf("%c", node.elem);
}

댓글

이 블로그의 인기 게시물

맥스 어만(Max Ehrmann) - 소망(진정 바라는 것)

진정 바라는 것                                                                       -맥스 어만 소란스럽고 바쁜 일상속에서도  침묵 안에 평화가 있다는 사실을 기억하십시오 포기하지 말고 가능한한 모든 사람들과 잘 지내도록 하십시오 조용하면서도 분명하게 진실을 말하고  어리석고 무지한 사람들의 말에도 귀를 기울이십시오  그들 역시 할 이야기가 있을테니까요  목소리가 크고 공격적인 사람들은 피하십시오  그들은 영혼을 괴롭힙니다 자신을 다른 사람들과 비교하면 자신이 하찮아 보이고  비참한 마음이 들수도 있습니다  더 위대하거나 더 못한 사람들은 언제나...