-
Notifications
You must be signed in to change notification settings - Fork 0
/
04-树7二叉搜索树的操作集.c
107 lines (102 loc) · 1.43 KB
/
04-树7二叉搜索树的操作集.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
BinTree Insert(BinTree BST, ElementType X)
{
if (!BST)
{
BinTree temp;
temp = (BinTree)malloc(sizeof (struct TNode));
temp->Left = NULL;
temp->Right = NULL;
temp->Data = X;
return temp;
}
else
{
if (X<BST->Data)
{
BST->Left = Insert(BST->Left,X);
}
else if(X>BST->Data)
{
BST->Right = Insert(BST->Right,X);
}
}
return BST;
}
Position FindMin(BinTree BST)
{
BinTree t;
t = BST;
if (t)
{
while (t->Left)
{
t = t->Left;
}
}
return t;
}
Position FindMax(BinTree BST)
{
BinTree t;
t = BST;
if(t)
{
while (t->Right)
{
t = t->Right;
}
}
return t;
}
Position Find(BinTree BST, ElementType X) {
if (!BST)
{
return NULL;
}
else if(X>BST->Data)
{
return Find(BST->Right,X);
}
else if (X<BST->Data)
{
return Find(BST->Left,X);
}
else
{
return BST;
}
}
BinTree Delete(BinTree BST, ElementType X) {
BinTree p;
if (!BST) {
printf("Not Found\n");
return BST;
}
if (X < BST->Data) {
BST->Left = Delete(BST->Left, X);
}
else if (X > BST->Data) {
BST->Right = Delete(BST->Right, X);
}
else {
if (BST->Left && BST->Right) {
p = FindMax(BST->Left);
BST->Data = p->Data;
BST->Left = Delete(BST->Left, BST->Data);
}
else {
p = BST;
if (!BST->Left) {
BST = BST->Right;
}
else if (!BST->Right) {
BST = BST->Left;
}
free(p);
}
}
return BST;
}
/*
用递归算法的时候,务必不要用新的结点指代形参。
*/