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
| #include <stdio.h>
#include <stdlib.h>
#include <time.h>
typedef struct BSNode
{
int value;
struct BSNode *lChild;
struct BSNode *rChild;
} BSNode;
BSNode *parent; //记录搜索时的父节点
//插入节点
void InsertNode(BSNode **node, int value)
{
if ((*node) == NULL)
{
(*node) = (BSNode *)malloc(sizeof(BSNode));
(*node)->value = value;
(*node)->lChild = NULL;
(*node)->rChild = NULL;
}
else if ((*node)->value == value)
{
printf("树中已存在 : %d\n", value);
}
else if ((*node)->value > value)
{
//小于根结点,递归放入左子树
InsertNode(&(*node)->lChild, value);
}
else
{
InsertNode(&(*node)->rChild, value);
}
}
//在树中查找key
BSNode *Search(BSNode *node, int key)
{
//Search结束或者找到则退出
if (node == NULL || node->value == key)
{
return node;
}
else if (node->value > key)
{
parent = node;
//根结点大于key,则递归查找左子树
return Search(node->lChild, key);
}
else
{
parent = node;
return Search(node->rChild, key);
}
}
//删除节点
void Delete(BSNode **node, int value)
{
BSNode *delNode = Search(*node, value); //查找待删除节点
if (delNode == NULL)
{
printf("没有找到待删除节点 : %d\n", value);
}
else if (delNode->lChild == NULL && delNode->rChild == NULL)
{
//若左右节点都为空,则直接删除
parent->rChild = NULL;
parent->lChild = NULL;
free(delNode);
printf("(1) : 已删除节点:%d\n", value);
}
else if (delNode->lChild == NULL || delNode->rChild == NULL)
{
//存在左节点或右节点,子承父业
BSNode *newNode = delNode->lChild == NULL ? delNode->rChild : delNode->lChild;
//若待删除节点是父节点的左子树
if (parent->lChild == delNode)
{
parent->lChild = newNode;
}
else
{
parent->rChild = newNode;
}
free(delNode);
printf("(2) : 已删除节点:%d\n", value);
}
else
{
//左右节点都不为空
BSNode *newNode = delNode->rChild;
if (parent->lChild == delNode)
{
parent->lChild = newNode;
}
else
{
parent->rChild = newNode;
}
free(delNode);
printf("(3) : 已删除节点:%d\n", value);
}
}
//中序遍历打印
void middleOrderPrint(BSNode *node)
{
if (node != NULL)
{
middleOrderPrint(node->lChild);
printf("%d ", node->value);
middleOrderPrint(node->rChild);
}
}
void printTree(BSNode *node)
{
printf("Tree : ");
middleOrderPrint(node);
printf("\n");
}
int main(int argc, char const *argv[])
{
BSNode *node;
srand(time(0));
int len = 30;
int randomIndex = rand() % (len - 1); //产生0-len中间的随机数
int value = -1;
int n;
for (int i = 0; i < len; i++)
{
n = rand() % 1000 + 50;
InsertNode(&node, n);
if (randomIndex == i)
value = n;
}
printTree(node);
printf("查找%d : %s\n", value, Search(node, value) == NULL ? "false" : "true");
Delete(&node, value);
printf("重新查找%d : %s\n", value, Search(node, value) == NULL ? "false" : "true");
printTree(node);
return 0;
}
|