-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbinary_search_tree.c
148 lines (138 loc) · 2.77 KB
/
binary_search_tree.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
/*
* @Description:
* @LastEditors: hsjfans
* @Email: [email protected]
* @Date: 2019-04-22 12:33:40
* @LastEditTime: 2019-04-23 20:31:54
*/
#include "include/binary_search_tree.h"
#include <stdlib.h>
// binary_search_tree_node is the node of binary tree
// contains the left child and right child node
struct binary_search_tree_node
{
struct binary_search_tree_node *left;
struct binary_search_tree_node *right;
Element val;
};
TreeNode *tree_node_new(Element e, SearchTree left, SearchTree right)
{
TreeNode *node = (TreeNode *)malloc(sizeof(TreeNode));
node->left = left;
node->right = right;
return node;
}
// recursive make node empty
SearchTree
make_empty(SearchTree t)
{
if (t)
{
make_empty(t->left);
make_empty(t->right);
free(t);
}
return NULL;
}
// recursive search node
Position find(Element e, SearchTree t, compare_func cmp)
{
if (t)
{
int cp = cmp(t->val, e);
if (cp == 0)
return t;
else if (cp > 0)
return find(e, t->left, cmp);
else
return find(e, t->right, cmp);
}
return NULL;
}
// the mininum value in tree the left leaf
Position find_min(SearchTree t)
{
if (t == NULL)
{
return NULL;
}
else if (t->left == NULL)
{
return t;
}
else
{
return find_min(t->left);
}
}
Position find_max(SearchTree t)
{
if (t == NULL)
{
return NULL;
}
else if (t->right == NULL)
{
return t;
}
else
{
return find_max(t->right);
}
}
// recursive insert
SearchTree insert(Element e, SearchTree t, compare_func cmp)
{
if (t == NULL)
{
t = tree_node_new(e, NULL, NULL);
return t;
}
int cp = cmp(e, t->val);
if (cp == 0)
return t;
else if (cp < 0)
t->left = insert(e, t->left, cmp);
else
t->right = insert(e, t->right, cmp);
return t;
}
SearchTree remove(Element e, SearchTree t, compare_func cmp)
{
SearchTree node = find(e, t, cmp);
if (node)
{
if (node->left != NULL && node->right != NULL)
{
SearchTree mini = find_min(node->right);
node->val = mini->val;
node->right = remove(mini->val, node->right, cmp);
}
else
{
if (node->left != NULL)
{
node = node->left;
}
else if (node->right != NULL)
{
node = node->right;
}
free(node);
}
}
return node;
}
int height(SearchTree t)
{
if (t == NULL)
{
return 0;
}
if (t)
{
int l = height(t->left);
int r = height(t->right);
return l > r ? l + 1 : r + 1;
}
}