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
| #include<stdio.h> #include <malloc.h>
typedef struct BSTNode { int key; struct BSTNode* left_child, * right_child; }BSTNode, * BSTree;
BSTNode* BST_Search(BSTree T, int key) { while (T != NULL && key != T->key) { if (key < T->key) { T = T->left_child; } else { T = T->right_child; } } return T; }
BSTNode* BSTSearch(BSTree T, int key) { if (T == NULL) { return NULL; } if (key == T->key) { return T; } else if (key < T->key) { BSTSearch(T->left_child, key); } else { BSTSearch(T->right_child, key); } }
void BST_Insert(BSTree &T, int value) { if (T == NULL) { T = (BSTree)malloc(sizeof(BSTNode)); T->key = value; T->left_child = T->right_child = NULL; printf("插入数据%d成功\n", value); } else if (value == T->key) { printf("存在相同的数据,插入失败!"); } else if (value < T->key) { BST_Insert(T->left_child, value); } else { BST_Insert(T->right_child, value); } }
void Create_BST(BSTree &T, int value[], int num) { T = NULL; int i = 0; while (i < num) { BST_Insert(T, value[i]); i += 1; } }
int main() { BSTree T; int data[] = { 50,66,60,26,21,30,70,68 }; Create_BST(T, data, (sizeof(data)/sizeof(data[0]))); BSTNode* result = BST_Search(T, 68); printf("查找结果为:%d", result->key); BSTNode* res = BSTSearch(T, 60); printf("\n递归查找结果为:%d", res->key); return 0; }
|