'알고리즘'에 해당되는 글 40건

문제 출처 : https://www.acmicpc.net/problem/1991

 

1991번: 트리 순회

첫째 줄에는 이진 트리의 노드의 개수 N(1≤N≤26)이 주어진다. 둘째 줄부터 N개의 줄에 걸쳐 각 노드와 그의 왼쪽 자식 노드, 오른쪽 자식 노드가 주어진다. 노드의 이름은 A부터 차례대로 영문자 대문자로 매겨지며, 항상 A가 루트 노드가 된다. 자식 노드가 없는 경우에는 .으로 표현된다.

www.acmicpc.net

이 문제는 이진 트리를 전위, 중위, 후위 순회를 하여서 출력하는 문제이다. 

이차원 배열을 선언하여 좌측 자식, 우측 자식 정보를 가지고 있는 배열을 만들어 문제를 해결하였다.

아래는 해당 문제를 풀이한 소스이다.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
#include<stdio.h>
#pragma warning(disable:4996)
char tree[30][3];
void preorder(int start)
{
    printf("%c", start + 'A');
    if (tree[start][0!= '.')
        preorder(tree[start][0- 'A');
    if (tree[start][1!= '.')
        preorder(tree[start][1- 'A');
}
void inorder(int start)
{
    if (tree[start][0!= '.')
        inorder(tree[start][0- 'A');
    printf("%c", start + 'A');
    if (tree[start][1!= '.')
        inorder(tree[start][1- 'A');
}
void postorder(int start)
{
    if (tree[start][0!= '.')
        postorder(tree[start][0- 'A');
    if (tree[start][1!= '.')
        postorder(tree[start][1- 'A');
    printf("%c", start + 'A');
}
int main()
{
    int Test;
    char x;
    scanf("%d%c"&Test,&x);
    char c;
    char left;
    char right;
    for (int i = 0; i < Test; i++)
    {
        scanf("%c %c %c%c"&c, &left, &right, &x);
        tree[c - 'A'][0= left;
        tree[c - 'A'][1= right;
    }
    preorder(0);
    printf("\n");
    inorder(0);
    printf("\n");
    postorder(0);
}
http://colorscripter.com/info#e" target="_blank" style="color:#4f4f4ftext-decoration:none">Colored by Color Scripter
블로그 이미지

뀨심볼

깃허브 주소는 : https://github.com/hhyc2 입니다~

,