二叉搜索树

定义:

·根结点的值比左子树任一结点的值大

·根结点的值比右子树任一节点的值小

·左子树与右子树也是二叉搜索树

1 struct node {
2     int value;
3     struct node* lson;
4     struct node* rson;
5 };
6 typedef struct node* tree;

 

操作:

 1 tree find(int x, tree root) {
 2     while (root) {
 3         if (x < root->value) {
 4             root = root -> lson;
 5         }
 6         else if (x > root->value) {
 7             root = root -> rson;
 8         }
 9         else {
10             return root;
11         }
12     }
13 
14     return NULL;
15 }
查找
 1 tree findMax(tree root) {
 2     if (root == NULL) {
 3         return NULL;
 4     }
 5 
 6     while (root -> rson) {
 7         root = root -> rson;
 8     }
 9     return root;
10 }
查找最大值
 1 tree findMin(tree root) {
 2     if (root == NULL) {
 3         return NULL;
 4     }
 5 
 6     while (root -> lson) {
 7         root = root -> lson;
 8     }
 9     return root;
10 }
查找最小值
 1 tree insert(int x, tree root) {
 2     if (root == NULL) {
 3         root = (tree)malloc(sizeof(struct node));
 4         root -> value = x;
 5         root -> lson = NULL;
 6         root -> rson = NULL;
 7     }
 8     else {
 9         if (x < root->value) {
10             root->lson = insert(x, root->lson);
11         }
12         else {
13             root->rson = insert(x, root->rson);
14         }
15     }
16 
17     return root;
18 }
插入
 1 tree delete(int x, tree root) {
 2     if (root == NULL) {
 3         printf("Not Found\n");
 4         return root;
 5     }
 6 
 7     if (x < root->value) {
 8         root->lson = delete(x, root->lson);
 9     }
10     else if (x > root->value) {
11         root->rson = delete(x, root->rson);
12     }
13     else {
14         if (root->lson && root->rson) {
15             tree t = findMin(root->rson);
16             root->value = t->value;
17             root->rson = delete(root->value, root->rson);
18         }
19         else {
20             tree t = root;
21             if (root->lson) {
22                 root = root->lson;
23             }
24             else if (root->rson) {
25                 root = root->rson;
26             }
27             else {
28                 root = NULL;
29             }
30             free(t);
31         }
32     }
33 
34     return root;
35 }
删除

 

你可能感兴趣的:(二叉搜索树)