-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy path2024.5.19.exercise.c
158 lines (147 loc) · 2.54 KB
/
2024.5.19.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
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
#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;
datatype* makesearchlist(int n)
{
datatype* searchlist = (datatype*)malloc(sizeof(datatype) * n);
if (searchlist == NULL)
{
printf("NULL\n");
return NULL;
}
int i;
for (i = 0; i < n; i++)
{
printf("请输入第%d个元素\n", i + 1);
scanf("%d", &searchlist[i]);
}
return searchlist;
}
tree* inserttree(tree* root, int key)
{
tree* father;
tree* pointer;
father = root;
pointer = root;
while (pointer != NULL)
{
father = pointer;
if (key > pointer->data)
{
pointer = pointer->right;
}
else
{
pointer = pointer->left;
}
}
tree* newnode = (tree*)malloc(sizeof(tree));
if (newnode == NULL)
{
printf("NULL\n");
return NULL;
}
newnode->data = key;
newnode->left = NULL;
newnode->right = NULL;
if (root == NULL)
{
root = newnode;
}
else if (key > father->data)
{
father->right = newnode;
}
else
{
father->left = newnode;
}
return root;
}
tree* creattree(datatype* searchlist, int n)
{
tree* root = NULL;
int i = 0;
for (i = 0; i < n; i++)
{
root = inserttree(root, searchlist[i]);
}
return root;
}
tree* searchtree(tree* root, int key, int* count)
{
tree* pointer = root;
while (pointer != NULL)
{
(*count)++;
if (pointer->data == key)
{
return pointer;
}
else if (pointer->data > key)
{
pointer = pointer->left;
}
else
{
pointer = pointer->right;
}
}
return pointer;
}
void displaytree(tree* root)
{
if (root != NULL)
{
printf("%d", root->data);
if (root->left != NULL || root->right != NULL)
{
printf("(");
displaytree(root->left);
if (root->left == NULL)
{
printf("NULL");
}
if (root->right != NULL)
{
printf(",");
}
displaytree(root->right);
printf(")");
}
}
}
int main()
{
printf("请输入要从几个元素中查找\n");
int n;
scanf("%d", &n);
datatype* searchlist = makesearchlist(n);
tree* root = creattree(searchlist, n);
displaytree(root);
printf("\n");
printf("请输入要查找的元素\n");
int key;
scanf("%d", &key);
int count = 0;
tree* result = searchtree(root, key, &count);
if (result == NULL)
{
printf("一共查找了%d次\n", count);
printf("无法找到\n");
}
else
{
printf("一共查找了%d次\n", count);
printf("成功找到了,值是%d\n", result->data);
}
return 0;
}