-
Notifications
You must be signed in to change notification settings - Fork 137
/
04_7_Binarysearch_tree_operation_set.cpp
98 lines (87 loc) · 1.84 KB
/
04_7_Binarysearch_tree_operation_set.cpp
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
/*
* 04_7_Binarysearch_tree_operation_set.cpp
*
* Created on: 2018年5月1日
* Author: SummerGift
*/
#include <stdio.h>
#include <stdlib.h>
typedef int ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree Insert( BinTree BST, ElementType X );
BinTree Delete( BinTree BST, ElementType X );
Position Find( BinTree BST, ElementType X );
Position FindMin( BinTree BST );
Position FindMax( BinTree BST );
Position FindMin(BinTree BST) {
if (!BST)
return NULL;
else if (!BST->Left)
return BST;
else
return FindMin(BST->Left);
}
Position FindMax(BinTree BST) {
if (BST) {
while (BST->Right)
BST = BST->Right;
}
return BST;
}
BinTree Insert(BinTree BST, ElementType X) {
if (!BST) {
BST = (BinTree) malloc(sizeof(struct TNode));
BST->Data = X;
BST->Left = BST->Right = NULL;
} else {
if (X < BST->Data)
BST->Left = Insert(BST->Left, X);
else if (X > BST->Data)
BST->Right = Insert(BST->Right, X);
}
return BST;
}
BinTree Delete(BinTree BST, ElementType X) {
Position tmp;
if (!BST) {
printf("Not Found\n");
} else {
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) {
tmp = FindMin(BST->Right);
BST->Data = tmp->Data;
BST->Right = Delete(BST->Right, BST->Data);
} else {
tmp = BST; //处理基本情况,也就是只有一个子节点或者没有子节点的情况
if (!BST->Left) {
BST = BST->Right;
} else {
BST = BST->Left;
}
free(tmp);
}
}
}
return BST;
}
Position Find(BinTree BST, ElementType X) {
while (BST) {
if (X > BST->Data)
BST = BST->Right;
else if (X < BST->Data)
BST = BST->Left;
else
return BST;
}
return NULL;
}