본문 바로가기
Computer Science

Tree PreOrder

by OKOK 2019. 1. 16.

1. tree

2. parent, child

3. 생각을 한 뒤에 풀이 가능

4. 사내에서 그 사람 코드 바로 보기 가능? 


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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
#include <stdio.h>
 
#define MAX_NODE_NUM 15
#define MAX_CHILD_NUM 2
 
typedef struct
{
    int parent;
    int child[MAX_CHILD_NUM];
} TreeNode;
TreeNode tree[MAX_NODE_NUM];
int nodeNum;
int edgeNum;
int root;
 
void initTree(void)
{
    int i;
    int j;
    for (i = 0; i <= nodeNum; i++)
    {
        tree[i].parent = -1;
        for (j = 0; j < MAX_CHILD_NUM; j++)
        {
            tree[i].child[j] = -1;
        }
    }
}
 
void addChild(int parent, int child)
{
    int i;
    for (i = 0; i < MAX_CHILD_NUM; i++)
    {
        if (tree[parent].child[i] == -1)
        {
            break;
        }
    }
    tree[parent].child[i] = child;
    tree[child].parent = parent;
}
 
int getRoot(void)
{
    int i;
    int j;
    for (i = 1; i <= nodeNum; i++)
    {
        if (tree[i].parent == -1)
        {
            return i;
        }
    }
    return -1;
}
 
void preOrder(int root)
{
    int i;
    int child;
    printf("%d ", root);
 
    for (i = 0; i < MAX_CHILD_NUM; i++)
    {
        child = tree[root].child[i];
        if (child != -1)
        {
            preOrder(child);
        }
    }
}
 
int main(void)
{
    freopen("input.txt""r", stdin);
    int test_case;
    int T;
    int i;
    int parent;
    int child;
 
    scanf("%d"&T);
 
    for (test_case = 1; test_case <= T; ++test_case)
    {
        scanf("%d %d"&nodeNum, &edgeNum);
 
        initTree();
 
        for (i = 0; i < edgeNum; i++)
        {
            scanf("%d %d"&parent, &child);
            addChild(parent, child);
        }
 
        root = getRoot();
 
        printf("#%d ", test_case);
        preOrder(root);
        printf("\n");
    }
 
    return 0;
}
cs

 


'Computer Science' 카테고리의 다른 글

queue  (0) 2019.01.17
stack  (0) 2019.01.17
Graph  (0) 2019.01.16
Linked List  (0) 2019.01.16
프유용 동적할당 대신 배열  (0) 2019.01.16

댓글