-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2024.4.6.exercise.c
130 lines (119 loc) · 2 KB
/
2024.4.6.exercise.c
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>
typedef int datatype;
typedef struct tree
{
datatype data;
struct tree* left;
struct tree* right;
}tree;
typedef struct list
{
tree* data;
struct list* next;
}list;
typedef struct queue
{
list* front;
list* rear;
}queue;
tree* creatnode(tree* root)
{
datatype element;
scanf("%d", &element);
if (element != 0)
{
root = (tree*)malloc(sizeof(tree));
if (root == NULL)
{
printf("NULL\n");
exit(1);
}
root->data = element;
root->left = NULL;
root->right = NULL;
root->left = creatnode(root->left);
root->right = creatnode(root->right);
}
return root;
}
void initqueue(queue* q)
{
q->front = q->rear = (list*)malloc(sizeof(list));
if (q->front == NULL)
{
printf("NULL\n");
return;
}
q->front->next = NULL;
}
bool isempty(queue* q)
{
if (q->front == q->rear || q->front->next == NULL)
{
return true;
}
return false;
}
void enqueue(queue* q, tree* root)
{
list* newnode = (list*)malloc(sizeof(list));
if (newnode == NULL)
{
printf("NULL");
return;
}
newnode->data = root;
newnode->next = NULL;
q->rear->next = newnode;
q->rear = newnode;
}
tree* outqueue(queue* q)
{
list* pointer;
tree* temp;
pointer = q->front->next;
temp = pointer->data;
q->front->next = pointer->next;
if (q->front->next == NULL)
{
q->rear = q->front;
}
free(pointer);
pointer = NULL;
return temp;
}
void visit(tree* root)
{
printf("%d ", root->data);
}
void preorder(tree* root)
{
queue q;
initqueue(&q);
tree* pointer = root;
enqueue(&q, root);
while (!isempty(&q))
{
pointer = outqueue(&q);
visit(pointer);
if (pointer->left != NULL)
{
enqueue(&q, pointer->left);
}
if (pointer->right != NULL)
{
enqueue(&q, pointer->right);
}
}
}
int main()
{
printf("ÇëÊäÈë½ÚµãÖµ\n");
tree* root = NULL;
root = creatnode(root);
preorder(root);
return 0;
}